Read Display JSON Data using jQuery AJAX

by Vincy. Last modified on July 13th, 2022.

In this tutorial, we are using jQuery for reading JSON data from a PHP page via AJAX. In PHP page we are reading an array of database records and convert them into JSON data using PHP json_encode().

Then, we are parsing JSON data and iterate object from jQuery function.

If you want to know more about JSON handling with PHP the linked article will be a comprehensive guide for you.

View DemoDownload

jQuery JSON Read Function

This function will be called on the click event of a reading button. It uses jQuery getJSON function to read a JSON data returned from a PHP page. It iterates JSON object array and appends results to HTML.

jquery-json-read

The code is,

function readJSONData() {
	$.getJSON("read_tutorial.php", function(data) {
		if (data) {
			var json_data;
			$('#read-data').hide();
			$('.demo-table').show();
			$.each(data, function(i, tutorial) {
				json_data = '<tr>' +
					'<td valign="top">' +
					'<div class="feed_title">' + tutorial.title + '</div>' +
					'<div>' + tutorial.description + '</div>' +
					'</td>' +
					'</tr>';
				$(json_data).appendTo('#demo-table-content');
			});
		} else {
			json_data += '<tr>' +
				'<td valign="top">No Tutorials Found</td>' +
				'</tr>';
			$(json_data).appendTo('#demo-table-content');
		}
	});
}

Create JSON Data in PHP

This PHP code reads data from the database. And then, using json_encode() function, it converts database result array into JSON formatted string.

It will be sent as the response to the jQuery getJSON request. The Code is,

<?php
require_once ("dbcontroller.php");
$db_handle = new DBController();
$query = "SELECT * FROM tutorial";
$result = $db_handle->runQuery($query);
print json_encode($result);
?>

Database Table SQL

CREATE TABLE IF NOT EXISTS `tutorial` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `rating` tinyint(2) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

View DemoDownload

 

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page