While JSON has many uses, probably the most common use is to pass data structures to Javascript. JSON is simply a standard format for data structures.
In this example we’ll use a PHP page as a JSON server; we’ll use an HTML page with embedded javascript to contact the server, retrieve the data and display it via an alert popup.
A JSON Server in PHP
First, the server. Our server here is very simple, but of course it could easily retrieve data from a database. The data structure that this example sends is also very simple, but JSON can send data structures that are as complex as you like.
<?php // Prevent caching. header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 01 Jan 1996 00:00:00 GMT'); // The JSON standard MIME header. header('Content-type: application/json'); // This ID parameter is sent by our javascript client. $id = $_GET['id']; // Here's some data that we want to send via JSON. // We'll include the $id parameter so that we // can show that it has been passed in correctly. // You can send whatever data you like. $data = array("Hello", $id); // Send the data. echo json_encode($data); ?>
Let’s imagine you run this on your local machine and access it with a URL like this: http://localhost/test.php?id=goodbye
What you get back looks like this:
["Hello","goodbye"]
Here we see some simple data in standard JSON format.
But it’s much more interesting to retrieve this data via javascript.
A Simple JSON Javascript Client
The following HTML page implements a simple javascript client that contacts our server, retrieves data via an AJAX call and displays it in an alert popup.
While you could make the AJAX call in pure unvarnished javascript, it’s much better to use a standard javascript library to hide browser and platform differences. In the following code we use the industry-standard free jQuery library, which downloads as a single file.
<html> <head> <script src="jquery-1.5.2.min.js"></script> <script language="javascript"> // This just displays the first parameter passed to it // in an alert. function show(json) { alert(json); } function run() { $.getJSON( "/test.php", // The server URL { id: 567 }, // Data you want to pass to the server. show // The function to call on completion. ); } // We'll run the AJAX query when the page loads. window.onload=run; </script> </head> <body> JSON Test Page. </body> </html>
Here’s the alert that this page pops up:
As you can see, our javascript has successfully retrieved data from the server.
jQuery also defines a more complex AJAX call routine, in case you want to check for possible failure or have a timeout or whatever.
All pages on this site are copyright © 2013 John W. Purcell
I am a newbie facing a problem that in php server if i define the code in function. say I have a function sayhello() which have all the code that you defined in server n returns the message.How to call that function in client.
Please reply asap
thanks
Hi Parveen,
Once again I have been horrendously late in replying to a comment, apologies. I have been moving countries from the UK to Hungary, that’s my excuse ….
What you need to do is pass some parameter to the PHP from your javascript (in the example I pass a parameter ‘id’ with value ’567′. Then in your PHP, check to see if the parameter has the value that signifies you want to call the function. Then run the function in PHP.
I’m assuming here that you have code in your PHP that you only want to run under certain conditions.
If you just want to put the above stuff in a function, all you have to do is run the function in PHP by writing myfunction() or whatever.
“/test.php”, // The server URL
Please correct me if I am wrong:
this indicates that both – the HTML and PHP are hosted on the same web-server … but incase the PHP is on a different server – we need to specify the entire web address.
Yes, you are correct. However, you cannot make a cross-domain query from AJAX as far as I know; this is barred for security reasons. (Sorry about the very late reply — I was swamped by spam! I’m going to add a captcha to sort out the spam problem).
Hopping on this bandwagon late, but you can use JSONP to make cross domain AJAX calls.
Thanks for a very helpful writeup!
hello I’ve tried this code but the server couldn’t retrieve the id and it returns it as null in $_get[$id]
any help?!!
Ouch! Check that the server works by itself before trying the javascript.
E.g. try
http://localhost/testing.php?id=something
in your browser. (Obvious, change the URL as appropriate).
If it doesn’t output ‘something’, then you have something misconfigured somewhere — an ancient version of PHP or something.
Let me know. If the above works, then it’s a client problem so we’re one step forwards …
how about the ‘echo json_encode($data);’ is inside a while loop is like
something like this..
$value)
{
if($postLabel == “search”)
{
//echo $value;
$qeryStrn = mysql_query(“SELECT * FROM db_profile WHERE (lname LIKE ‘$value%’) ORDER BY lname”)or die(mysql_error());
while($row = mysql_fetch_array($qeryStrn))
{
$getValues = array();
$getValues[] = array(“lastname” => $row['lname'], “firstname” => $row['fname'], “housenumber” => $row['house_no']);
echo json_encode($getValues) . “\n”;
}
}
}
}
?>
then on ajax, javascript part
if(this.readyState == 4 && this.status == 200 && this.responseText != “”)
{
var objNotation = this.responseText;
alert(JSON.parse(objNotation));
}
the browser can’t even alert it..
You need to have just one json_encode creating all your output, as far as I know. It’s a while since I looked at this stuff, but as I remember, you need to have one json data structure that the browser parses. You need to store all your rows in an array or something, then output that data structure as a single thing.
Thanks lot for nice JSON tutorial. It helped me lot especially comments….