Simple AJAX with jQuery

jQuery AJAXJQuery includes powerful ajax features for enriching the experience of a web application. This post will describe the simplest case, using ajax to replace part of a page with new content from the server. The server-side technology can be anything, however ASP.NET webforms makes things more difficult.

An example situation where this technique might be useful is in a master-detail scenario. As the user selects a item from a list the details of that item should be displayed somewhere else on the page. Here is my list of items and the container that will hold the details when an item is selected:

<p><a href="#" onclick="AJAX.ajaxLoad(1);">Option 1</a></p>
<p><a href="#" onclick="AJAX.ajaxLoad(2);">Option 2</a></p>
<p><a href="#" onclick="AJAX.ajaxLoad(3);">Option 3</a></p>

<div id="details">Please select an option from the list above.</div>

You can see that when an option is selected a javascript function called AJAX.ajaxLoad() will be invoked. This function will use jQuery to perform an ajax request to the server, and then update the page with the result. By default jQuery will cache all requests in internet explorer. To disable this behaviour use $.ajaxSetup().

var AJAX = {}; // declare a namespace

AJAX.ajaxLoad = function(id) {
    
    $.ajaxSetup ({
        // Disable caching of AJAX responses */
        cache: false
    });

    $('#details').load('/url_to_get_details/' + id);    
}

This method will call /url_to_get_details/id which must return a html fragment which will be placed in the details div, overwriting anything that is already there.


Comments

Comments are closed