In this screencast we explore the jQuery $.post() command in order to create a simple AJAX login script that also gracefully degrades and works for users who do not have JavaScript enabled.
You may want to check out my post "What Exactly is JSON?" if you're not familiar with the JavaScript Object Notation before watching.
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';
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');
This is the first in a series of screencasts that I'm creating to highlight the AJAX functionality present in the open source Javascript framework jQuery. In this screencast I give a brief overview of AJAX as well as delve into our first jQuery command.
AJAX stands for Asynchronous JavaScript and XML.