How to write an AJAX application with jQuery

As of now, AJAX is a must to have in recent web application including CMS. Drupal 5.0 has selected jQuery as its core JavaScript backend as well as AJAX engine. In this article, I will give a brief example how to develop a simple AJAX application with jQuery.

Basically, AJAX is nothing special but the JavaScript such that retrieves data from the server without refreshing the whole page. There are many compatibility problems to write AJAX for cross-browser. jQuery could handle all that issues and it is just 15 kb in size.

Let's see what I have. Supposing I have a web form with a button as follow.


And I have a div for displaying whatever I got from the AJAX.

You may handle this button by specifying its onclick and onsubmit of that form.

var button = $('#call-button').get(0);
button.onclick = function() {
    execute_call();
}
button.form.onsubmit = function() {
    return false;
}

Just like above. Everytime visitors press this button, execute_call() will be executed immediately. Now I will call an AJAX.

function execute_call() {
    $.ajax({
        type: "GET",
        url: "http://domain.com/",
        data: "param="+encodeURIComponent("data"),
        success: function(data) {
            $('#call-wrapper').html(data);
        },
        error: function(xmlhttp) {
            $('#call-wrapper').html(xmlhttp.status);
        }
    });
}

That means it would try to submit a query with method GET to the specified url and the data. If the query went well, the result content will be passed through the given function to display them in given div. Otherwise, something went wrong, the response status will be displayed instead.

Tags: , ,

Post new comment