JSON can be used as a lightweight exchange format on many web contexts. One of its many implementations is requesting data from a database and showing the results as HTML. jQuery provides us with the $.getJSON()
method to be used in these cases.
An AJAX request (usually a GET request) must be sent to a server-side script which processes the query and returns an output in JSON format. In this case we're going to use a mock PHP script that simply returns a definition:
<?php
header('Content-Type: application/json');
$request = strtolower($_REQUEST['word']);
if(!ctype_alpha($request)) {
$error = array('error' => 'Not a valid word');
echo json_encode($error);
exit();
}
$words = array(
'css' => 'A stylesheet language',
'dom' => 'A document model interface',
'xml' => 'A structured markup language',
'javascript' => 'A client-side web programming language'
);
if(array_key_exists($request, $words)) {
$output = array('definition' => $words[$request]);
echo json_encode($output);
}
?>
This script is very simple. It simply expects a word
parameter to be passed along with the request. In this example we're going to use a select box with a change
event attached to it:
$(function() {
$('#definitions').on('change', function() {
var select = $(this);
var value = $('option:selected', select).val();
$.getJSON('json.php', { word: value }, function(data) {
var html = '<dt>' + value.toUpperCase() + '</dt>';
html += '<dd>' + data.definition + '</dd>';
$('#output').html(html);
});
});
});
$.getJSON()
works this way:
- The first parameter is the URL of the server-side script.
- The second parameter is the request data, passed as an object literal where a property is a request parameter and a value is the parameter's value. jQuery automatically converts this object to a plain query string, as it was
word=value
. - The third parameter is the callback function which contains a reference to the returned JSON object (
data
).
In this example the server-side script returns the following JSON object when our request is successful:
{
"definition": "Definition"
}
When a request is malformed, it returns an error JSON object:
{
"error": "Not a valid word"
}
To check whether a request has been successful or not, we can simply verify the presence of the error
property:
if(typeof data.error !== 'undefined') {
// Error!
}
You can see the example in the following video.