Print Dynamic Content using JavaScript, jQuery, and PHP
The print is a very useful feature for any data management section. Generally, the print option is used in the web application to save data for offline use. There are various plugins available to print web page content using jQuery. Alternatively, you can print the web page content using window print() method in JavaScript. In this case, the static data or div content of the current window is printed.
You can easily print the content of a specific div using JavaScript. But, some cases you need to allow the user to print dynamic content from the database without previewing in the web page. To integrate this functionality, the dynamic content needs to be loaded from the server-side and print dynamic div content on the fly. In this tutorial, we will show you how to load dynamic content in the hidden div and print the content of hidden div using JavaScript, jQuery, Ajax, PHP, and MySQL.
To demonstrate the dynamic div content print functionality, the following steps will be implemented.
- Display dropdown element to select a specific user.
- Load the selected user’s details from the database.
- Print dynamic user data on the fly without preview on the web page.
Create Database Table
To store user’s information a table need to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database.
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, `status` enum('Active','Inactive') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Active', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Database Configuration (dbConfig.php)
The dbConfig.php file is used to connect and select the database. Specify the database host ( $dbHost ), username ( $dbUsername ), password ( $dbPassword ), and name ( $dbName ) as per your MySQL database credentials.
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) die("Connection failed: " . $db->connect_error);
>
Print Dynamic Content (index.php)
HTML & PHP:
Initially, all the users are fetched from the database and listed in the dropdown. A specific user needs to be selected to print the details information of the user from the database.
- Dropdown – Helps to list and select the user.
- Print button – Initialize the print.
- Hidden div – Holds the dynamically generated content that retrieved from the database.
// Include the database configuration file
require_once 'dbConfig.php';
// Fetch the users from the database
$result = $db->query("SELECT id, name FROM users");
?> select id="userSelect"> option value="">Select User option> while($row = $result->fetch_assoc()) ?> option value=" echo $row['id']; ?>"> echo $row['name']; ?> option> > ?> select> button id="getUser">Print Details button> div id="userInfo" style="display: none;"> div>
JavaScript:
Include the jQuery library.
script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> script>
The following code loads the dynamic content from the server-side and prints specific div content with window print() method.
- Get the selected user ID.
- Load data from the server-side script ( getData.php ) and puts dynamic content in the specific element using jQuery load() method.
- Open the Print Dialog to let the user print the dynamic content of the specific hidden div using window print() method.
script> $(document).ready(function( )< $('#getUser').on('click',function( )< var userID = $('#userSelect').val(); $('#userInfo').load('getData.php?id='+userID,function( )< var printContent = document.getElementById('userInfo'); var WinPrint = window.open('', '', 'width=900,height=650'); WinPrint.document.write(printContent.innerHTML); WinPrint.document.close(); WinPrint.focus(); WinPrint.print(); WinPrint.close(); >); >); >); script>
Load Dynamic Data (getData.php)
The getData.php file is loaded by the AJAX load() method to retrieve the user data from the database using PHP and MySQL.
- The specific user’s ID is retrieved from the query string of the URL.
- The data is fetched from the users table based on the specific ID.
- The user details are rendered and dynamic content is returned to the load() method.
$userData = array();
if(!empty($_GET['id'])) // Include the database configuration file
require_once 'dbConfig.php';
// Get the user's ID from the URL
$userID = $_GET['id'];
// Fetch the user data based on the ID
$query = $db->query("SELECT * FROM users WHERE color: #007700">.$userID);
if($query->num_rows > 0) $userData = $query->fetch_assoc();
>
>
?> div class="container"> h2>User Details h2> if(!empty($userData)) ?> p>b>Name: b> echo $userData['name']; ?> p> p>b>Email: b> echo $userData['email']; ?> p> p>b>Phone: b> echo $userData['phone']; ?> p> p>b>Created: b> echo $userData['created']; ?> p> p>b>Status: b> echo $userData['status']; ?> p> >else ?> p>User not found. p> > ?> div>
Conclusion
Most cases, the print option is used to print the content that already displayed on the web page. For this common purpose, you can use window print() method to allow the user to select preferred printing options. You can also let the user print the specific div content or content of the specific element. The example code provided here is useful when you want to print dynamic data from the database on the fly without a preview on the web page. Also, it will provide a solution to print the content of a hidden div using JavaScript.
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question
Динамические страницы в PHP
Динамическая страница — это PHP скрипт, который в зависимости от URL отображает разный контент.
В этом уроке мы сделаем такую страницу с помощью GET-параметров.
Создание динамической страницы
Чтобы показывать пользователю разные страницы, сначала нужно подготовить контент для каждой из них. Пусть все страницы лежат в двумерном массиве:
'Создание динамических страниц', 'content' => 'Текст статьи про динамические страницы.' ], [ 'title' => 'Как поймать котёнка', 'content' => 'Текст статьи про котят.' ] ];
Контент готов, теперь определимся с навигацией по страницам.
Представим, что URL нашего скрипта /index.php . Нам необходимо сделать уникальный URL для каждой страницы.
Для этого мы добавим в URL GET-параметр под названием id, который будет содержать в себе номер статьи. Например /index.php?id=5 будет означать, что нужно отобразить пятую статью.
В качестве номеров мы можем использовать ключи массива со статьями. У нас ведь сейчас есть 2 статьи, одна с индексом 0, другая с индексом 1, верно?
Array ( [0] => Array ( [title] => Создание динамических страниц [content] => Текст статьи про динамические страницы. ) [1] => Array ( [title] => Как поймать котёнка [content] => Текст статьи про котят. ) )
Вот эти числа у нас и будут идентификаторами. Теперь напишем простенькое меню с новыми URL-адресами:
В коде выше мы выводим ссылку на главную статью и по персональной ссылке для каждой статьи.
Теперь нам нужно при наличии GET-параметра id отобразить контент соответствующей статьи. Сам id у нас лежит в переменной $_GET[‘id’] .
Получить статью по id очень просто:
$article = $articles[$_GET['id']]; echo $article['title'];
Т.е. мы по идентификатору статьи получаем массив с этой самой статьёй.
Далее есть смысл добавить 2 условия: на наличие id в URL и на существование статьи с конкретным id. Если id нет — тогда укажем, что это главная страница, а если id есть, но некорректный — можно показать сообщение с ошибкой:
Главная'; // Если id есть, но нет статьи с таким id - показываем ошибку elseif(!isset($articles[$_GET['id']])) echo 'Ошибка: страница не существует.
'; // Если id есть и статья с таким id существует - выводим статью else < $article = $articles[$_GET['id']]; echo '' . $article['title'] . '
'; echo '' . $article['content'] . '
'; >
Динамическая страница готова! Ещё раз весь код:
'Создание динамических страниц', 'content' => 'Текст статьи про динамические страницы.' ], [ 'title' => 'Как поймать котёнка', 'content' => 'Текст статьи про котят.' ] ]; ?> Главная
$article): ?> ">
Главная'; // Если id есть, но нет статьи с таким id - показываем ошибку elseif(!isset($articles[$_GET['id']])) echo 'Ошибка: страница не существует.
'; // Если id есть и статья с таким id существует - выводим статью else < $article = $articles[$_GET['id']]; echo '' . $article['title'] . '
'; echo '' . $article['content'] . '
'; >
Теперь вы можете создавать динамические сайты, на которых количество страниц зависит только от количества элементов массива, и никаких десятков html-файлов. 🙂
Если на сайте должны быть разные типы страниц, например статья и товар, можно добавить ещё один GET-параметр, отвечающий за тип страницы: /index.php?type=article&id=5 .
Конечно, эта система не идеальна. Гораздо интересней смотрелись бы URL вида /articles/5 или /dinamicheskie-stranicy-v-php (как у статьи, которую вы сейчас читаете).
В ближайшее время я добавлю новую статью про полноценное ЧПУ (человеко-подобные URL) и подробно объясню, как это делается.