Read Display JSON Data using jQuery AJAX

by Vincy. Last modified on October 12th, 2022.

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

Then, we are parsing JSON data and iterating objects from the jQuery function.

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

View Demo

jQuery JSON Read Function

This function will be called on the click event of a reading button. It uses jQuery getJSON function to read 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() {
	$('#loader-icon').css("display", "inline-block");
	$.getJSON("read-tutorial-ajax.php", function(data) {
	})
		.done(function(data) {
			var json_data;
			$('#read-data').show();
			$('.demo-table').show();
			$('#demo-table-content').empty();
			$.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');
			})
			$('#loader-icon').hide();
		})
		.fail(function() {
			var json_data;
			$('#read-data').show();
			$('.demo-table').show();
			$('#demo-table-content').empty();
			json_data = '<tr>' +
				'<td valign="top">No Tutorials Found</td>' +
				'</tr>';
			$(json_data).appendTo('#demo-table-content');
			$('#loader-icon').hide();
		})
}

HTML to display the read-JSON trigger and result on the UI

This HTML code will show a button “Read JSON Data” on the UI when landing. On its click, it calls the readJSONData() function we saw in the above section.

The JSON data returned by the server is appended to the target HTML DIV tag “demo-table-content” row by row.

<html>
<head>
<title>Read Display JSON Data using jQuery AJAX</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets/css/styles.css" rel="stylesheet" type="text/css">
<script src="https://code.jquery.com/jquery-3.6.1.min.js"
    integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
    crossorigin="anonymous"></script>
<script type="text/javascript" src="assets/js/read-json.js"></script>
</head>
<body>
    <div id="read-data">
        <button class="btnRead" onClick="readJSONData();">Read JSON Data</button>
        <div id="loader-icon">
            <img src="loader.gif" id="image-size" />
        </div>
    </div>
    <table class="demo-table">
        <tbody id="demo-table-content">
        </tbody>
    </table>
</body>
</html>

Create JSON Data in PHP

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

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

<?php
$connection = mysqli_connect("localhost", "root", "", "db_json_read");
$sql = "SELECT * FROM tutorial";
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->get_result();
$resultSet = array();
while ($row = $result->fetch_assoc()) {
    $resultSet[] = $row;
}
if (! empty($resultSet)) {
    print json_encode($resultSet);
}
?>

Database Table SQL

This SQL script contains the target database table structure and some initial data. By importing this script before running this example, you can see the expected result without causing any errors.

With no data, this read-JSON example will show the message “No records found” on the UI.

CREATE TABLE `tutorial` (
  `id` int(8) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `rating` tinyint(2) DEFAULT NULL
);

--
-- Dumping data for table `tutorial`
--

INSERT INTO `tutorial` (`id`, `title`, `description`, `rating`) VALUES
(1, 'Favorite Star Rating with jQuery', 'This tutorial is for doing favorite star ratings using jQuery. It displays list of HTML stars by using li tags. These stars are highlighted by using CSS and jQuery based on the favorite rating selected by the user.', 1),
(2, 'PHP RSS Feed Read and List', 'PHP\'s simplexml_load_file() function is used for reading data from XML file. Using this function, we can parse RSS feed to get item object array.', 3),
(3, 'jQuery AJAX Autocomplete – Country Example', 'Autocomplete feature is used to provide an auto suggestion for users while entering input. It suggests country names for the users based on the keyword they entered into the input field by using jQuery AJAX.', 5);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tutorial`
--
ALTER TABLE `tutorial`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tutorial`
--
ALTER TABLE `tutorial`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

View DemoDownload

Leave a Reply

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

↑ Back to Top

Share this page