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.
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.
JSON Test Page.
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.