May 16, 2013 5503 Views 1 Comment

Working With JSON, JQuery, PHP and Mysql


JSON stands for JavaScript Object Notation and is an excellent alternative to XML. Storing data with JSON creates JavaScript objects which can be easily parsed and manipulated. Learn how to pass JSON output to JQuery, parse JSON data with JQuery and finally inserting it into the DOM.


Getting data from MYSQL Database and returning as JSON Object using PHP

The magic here is the json_encode function. This nifty little php function is used to transform our array to JSON.

$db = mysqli_connect("localhost","root","","mylogs");
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);


Parsing JSON Using Jquery

Below is the jQuery code which parses JSON string using $.parseJSON(); method to Javascript Object. Next, we iterate over the javascript fetching each value using the corresponding index.

var formhtml = "logreq=1";
var postURL= "process.php";
type: "POST",
url: postURL,
data: formhtml,
success: function(html){
var output= "<table><tbody><thead><th>Log</th><th>Username</th><th>Date</th><th>Event</th></thead>";
var logsData = $.parseJSON(html);
for (var i in logsData.logs){
output+="<tr><td>" + logsData.logs[i].title + "</td><td>" + logsData.logs[i].user + "</td><td>" + logsData.logs[i].date+ "</td><td>" + logsData.logs[i].log+"</td></tr>";
error: function (html) {
alert("Oops...Something went terribly wrong");

The Front-End

Jquery is used to update the contents of the div with id “log_container”

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src=""></script>
<script type="text/javascript" src="js/script.js"></script>
<title>KodeSmart | Working With JSON Tutorial</title>
<div id="log_container">

  • Terry

    I generally work with PHP and MySQL. I like how clean the coding can be and what you can make it do for your website. I have never worked with JSON or jQuery other than code that you plugin and is easy to implement.