Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
From the author of

Applying Ajax

The core of Ajax contains two parts: the JavaScript that calls a server-side script, and the server-side script that responds. I think it’s easiest to begin with the server-side script, so you best know what the client-side JavaScript should be doing.

The server-side PHP script, called login_ajax.php, just needs to replicate the process that you’ve already seen for the standard, non-JavaScript validation. The only difference-and it’s a significant one-is that the results of the PHP script will only be “seen” by the JavaScript, which is to say that the PHP script will contain no HTML and should only return some data indicating the results. This data could be in XML or JSON format, but in this example, the data will only be a simple string, as that format can convey enough information.

The PHP script would expect to receive two values in the URL: an email address and a password. These two values need to be validated and checked against those in the database. If two values are not provided, the script merely prints INCOMPLETE. If the email address is invalid, the script prints INVALID_EMAIL. If both values are provided but don’t match those previously stored, the script prints INCORRECT. Finally, if both values are provided and match those in the database, the script starts the session and prints CORRECT. Remember that this script will not be seen by the end user and what it prints will be read in by the client-side JavaScript. Check out the downloaded script to see the full code.

With the server-side script written, you can create the JavaScript that calls that script. As just explained, the JavaScript needs to send to the script an email address and a password, via the GET method, and will receive a string back. Using jQuery to perform Ajax calls is rather straightforward. Start by creating an object that will store the form data:

var data = new Object();
data.email = email;
data.password = password;

The first line creates a generic JavaScript object. Then an email property is created and assigned the value of the email variable. This is repeated for the password property. The names of the properties here will create the names of the variables received by the server-side PHP script.

Next, create another object for setting the Ajax options:

var options = new Object();

This new object’s first property needs to be data, in order to transmit the data to the server-side script.

options.data = data;

Next, set the type of data expected in return, and the type of request being made:

options.dataType = 'text';
options.type = 'get';

Next, identify the URL to request:

options.url = 'login_ajax.php';

Finally, begin creating a function to be called when the server responds:

options.success = function(response) {
    if (response == 'CORRECT') {
        $('#flexArea').html('<h1>Welcome</h1><p>Welcome back, user!</p>');
    } else {

The function receives the server response as its lone argument, assigned to the response variable. If the value of that variable, the value being the entire response from the server, equals CORRECT, then the flexArea div, which holds the login form, is replaced by other content. If that’s not the server response, then the errors have to be handled accordingly.

var message;
switch (response) {
    case 'INCORRECT':
        message = 'The submitted credentials do not match those on file!';
        break;
    case 'INCOMPLETE':
        message = 'Please provide an email address and a password!';
        break;
    case 'INVALID_EMAIL':
        message = 'Please provide your email address!';
        break;
}
if ($('#responseP').length) {
    $('#responseP').text(message);
} else {
    $('#loginForm').prepend('<p id="responseP" class="error">' + message + '</p>');
}

In that code, a switch compares the server response against three different strings. Depending upon the value, a different string message is identified. This message then needs to be added to the page, within the login form (see Figure 3). To do that, invoke jQuery’s prepend() method, creating a new paragraph with an id of response, a class of error, and the message string. Because it’s possible that this paragraph already exists (e.g., the user fails to provide a valid email address the first time and fails to provide correct credentials the second), the code first checks to see if the paragraph exists, and just updates its text if it does.

Figure 3

Figure 3 An error message derived from the server response has been added before the form.

Finally, you have to complete the main if-else, the anonymous function, and the statement assigning this function to the Ajax option’s success property:

    }	
}; // End of success.

Once you’ve done all that, you can perform the actual Ajax request:

$.ajax(options);

And that takes care of it.

Conclusion

Adding Ajax to a login form makes for a smooth, professional user experience, and is easy enough to do thanks to a powerful framework such as jQuery. The real trick is ensuring that you’re not leaving other users behind: those with legacy or non-standard browsers. The solution is to apply progressive enhancement: Create the basic functionality, then add a layer of enhanced behavior on top. Doing this correctly can complicate the logic a bit, but the reliability of the end result makes it entirely worth it.

  • + Share This
  • 🔖 Save To Your Account