jQuery Ajax Example and Tutorial

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will show you an simple contrived example of a html page which makes an AJAX calls to a PHP server page to retrieve some data.

View live demo.

The page is going to look like this …

jquery ajax example

jquery ajax example

The key here is that the capital city is loaded without a page refresh.  This is what is meant by AJAX, which stands for Asynchronous Javascript and XML — the key word being asynchronous.

1.  Start with a template HTML5 page with a jQuery CDN script reference and its document ready event handler at the bottom…

page framework

page framework

2.  We also added in the select droplist and paragraph text.  The span with id=”capital” is where we will insert our dynamic data, which is the capital city.

3.  Data is retrieved by calling an PHP page which will return the capital city if you provide the state in the query string …

php page

php page

4. For the purpose of this example, we are only handling 4 states.  And the complete code for the PHP file called “computecapitals.php” is …

php code

php code

5.  We call this PHP code via a jQuery AJAX method by $.get as shown below…

ajax  get

ajax get

Within our document ready, we retrieve the selected state from the droplist into the variable “selectedState”.  We concatenate that value into the querystring for computecapitals.php to construct the URL destination of our AJAX call.   This URL is the first thing we pass into our $.get AJAX call.  The other thing we pass into it is a callback function which will be invoked when the URL has finished loading.

When the callback function is invoked (this function has no name, it is an anonymous function), we should have the retrieved data (the capital city) in the “data” object.

We stuff that data into the html of the span tag with id of “capital”.

View demo here.