Read Display JSON Data using jQuery AJAX

In this tutorial we are using jQuery for reading JSON data from a PHP page via AJAX. In PHP page we are reading array of database records and covert them into JSON data using PHP json_encode(). Then, we are parsing JSON data and iterate object from jQuery function.

jquery-json-read

View DemoDownload

jQuery jSON Read Function

This function will be called on the click event of read button. It uses jQuery getJSON function to read a JSON data returned from a PHP page. It iterates JSON object array and append results to HTML. 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 of the jQuery getSON 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

This jQuery code tutorial was published on November 12, 2014.

↑ Back to Top