What exactly is JSON?
JSON is short for JavaScript Object Notation. It's a notation used to create JavaScript objects.
JSON looks like this:
{
name: "Shawn McCool",
language: "English"
}
When evaluated by JavaScript or decoded with another language you'd end up with an object like the one below.
person.name is equal to "Shawn McCool" person.language is equal to "English".
Since using JSON allows you to easily serialize arrays and objects, it's often used during AJAX calls and web services. Below are some examples of the JavaScript Object Notation.
var myArray = ['cat', 'dog'];
var myObject = {animal: 'cow'};
alert(myArray[0]); // outputs 'cat'
alert(myObject.animal); // outputs 'cow';
A standard set of interactions for an AJAX login script might be:
JavaScript client (browser) posts username and password to PHP.
$.post('/ajax.php', { username: $('input[name=username]').val(), password: $('input[name=password]').val() }, function(data) {}, 'json');PHP authenticates the information against the database then generates a response which is json_encoded and sent to the browser.
$user = $this->auth_model->Login($_POST['username'], $_POST['password']); if($user) $data['success'] = true; else $data['success'] = false; echo json_encode($data);JavaScript client ‘eval’uates the JSON which creates an object. JavaScript client then determines behavior based on the data in the object.
$.post('/ajax.php', {username: $('input[name=username]').val(), password: $('input[name=password]').val()}, function(data) { if(data.success) { // login succeeded } else { // login failed } }, 'json');