JQuery and Ajax – asynchronous data load

Here are a few ways to get data asynchronously using JQuery and Ajax.
Let's start with a dropdown.

<select><option>Option 1</option><option>Option 1</option><option>Option 1</option>
</select>

Now we will fill it with data from a database. I won't go into the details of the server-side script, but let's assume that it returns a string of HTML in the correct format to use in a dropdown box.

<select id="combo" name="combo"></select>

Example 1 - this will simply load the HTML into the element:

$("#combo").load("serverscript.php?q=1&amp;p=45");

Example 2 - this will load the HTML into a variable which you can then use:

var content;
$.get("serverscript.php?q=1&amp;p=45", function(data){
    content= data;
});
$("#combo").append(content);

Example 3 - this is an extension of Example 2 and does not cache the variable. It just calls a function with the data variable:

$.get("serverscript.php?q=1&amp;p=45", PopulateSelectBox);

//   the content variable will store the output of the .get ajax call
function PopulateSelectBox(content) {
   $("#combo").append(content);
}

The great thing about Example 2 and 3 is that you can massage the data before putting it into the element. Similarly, you can handle the element change effectively. For example, the dropdown box element may already have values in it and you're database call is updating the element. When you have the content from the call, you can decide to .prepend or .append the content.

Possibilities are almost endless. I really like Ajax 🙂

Til next time ...