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.

<?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);
}

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.
<?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.

  • 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.
<?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

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.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

2 Comments

  1. Ismail Nuhu Said...
  2. Robert Said...

Leave a reply

keyboard_double_arrow_up