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.
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;
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.
<?php
// 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);
}
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.
<?php
// Include the database configuration file
require_once 'dbConfig.php';
// Fetch the users from the database
$result = $db->query("SELECT id, name FROM users");
?> <!-- Dropdown to select the user --> <select id="userSelect"> <option value="">Select User</option> <?php while($row = $result->fetch_assoc()){ ?> <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option> <?php } ?> </select> <!-- Print button --> <button id="getUser">Print Details</button> <!-- Hidden div to load the dynamic content --> <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.
getData.php
) and puts dynamic content in the specific element using jQuery load() 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>
The getData.php
file is loaded by the AJAX load() method to retrieve the user data from the database using PHP and MySQL.
load()
method.<?php
$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 id = ".$userID);
if($query->num_rows > 0){
$userData = $query->fetch_assoc();
}
}
?> <!-- Render the user details --> <div class="container"> <h2>User Details</h2> <?php if(!empty($userData)){ ?> <p><b>Name:</b> <?php echo $userData['name']; ?></p> <p><b>Email:</b> <?php echo $userData['email']; ?></p> <p><b>Phone:</b> <?php echo $userData['phone']; ?></p> <p><b>Created:</b> <?php echo $userData['created']; ?></p> <p><b>Status:</b> <?php echo $userData['status']; ?></p> <?php }else{ ?> <p>User not found...</p> <?php } ?> </div>
Print a Specific Area of the Web Page using jQuery
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.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thank you so much.
But how can I add image to be included on the content to print?
Thank you so much guys. You were my last stop on this.