How to work with Ajax PHP and JSON

Example for get data from database in json format with use of php and ajax. Get json data from server in 2 easy steps. If you are beginner for Ajax and PHP with jQuery, you will found this article helpful. Here is simple step by step example given for Ajax PHP and jQuery use.

Example with json data in array:

Step 1:
Create php file for handle ajax request and return json response. e.g., data.php

<?php

//define array
$jsonArr = array();

//fire query on db
$res = mysql_query('SELECT ......');

//prepare associative array from result
while($row = mysql_fetch_assoc($res))
{
    $jsonArr[] = $row;
}

header('Content-type: application/json;');
echo json_encode($jsonArr);
exit;

?>

Step 2:
Call data.php file and get json response.

$.ajax({
    url: "data.php",
    data: '{IF ANY}',
    contentType: 'application/json',
}).done(function(data) {
    console.log(data);
});

//output like this
[{"key":"val"}, {"key":"val"}, ....]

Example with single json data:

Step 1:
Create php file for handle ajax request and return json response. e.g., data.php

<?php

//fire query on db
$res = mysql_query('SELECT ......');

//suppose your query give result in one row
$jsonArr = mysql_fetch_assoc($res)

header('Content-type: application/json;');
echo json_encode($jsonArr);
exit;

?>

Step 2:
Call data.php file and get json response.

$.ajax({
    url: "data.php",
    data: '{IF ANY}',
    contentType: 'application/json',
}).done(function(data) {
    console.log(data);
});

//output like this
{"key":"val"}