jQuery Ajax Function Example

Let's have a closer look at the jQuery .ajax() function.

Demo Code Download

Description

The jQuery library has a full suite of AJAX capabilities which allows us to load data from a server without refresh the browser page. In this section, we will have a quick look at refreshing page content, loading scripts and retrieveing data from different web pages/servers.

$.ajax()

$.ajax() is arguably the most revolutionary jQuery function. It provides us with means of dynamically loading content, scripts and data and using them on our live web page. Other common uses include submitting a form using AJAX and sending data to server side scripts which can store it in a database.

Important AJAX settings to note:

  • url - The target of the request.
  • type - The type of HTTP request either: "GET" (Default) or "POST".
    Difference between GET and POST.
  • async - Set asyncronous to TRUE if you want it to load in background and this will allow you to run mutiple AJAX requests at the same time. If you set to FALSE the request will run and then wait for the result before preceeding with the rest of you code.
  • data - Specify data you wish to pass with the AJAX call in "{param1: 'value1'}" format.
  • dataType - Specify the type of data that is returned: "xml/html/script/json/jsonp".
  • success - The function that is fired when the AJAX call has completed successfully.
  • error - The function that is fired when the AJAX call encountered errors.
  • jsonp - Allows you to specify a callback function when making cross domain AJAX calls.
  • timeout - You can also set a timeout on the AJAX call in milliseconds.

As you can see $.ajax() has lots of settings (I have only listed the main ones above). In light of this, they have provided us with many shorthand methods already contain the settings we require. I know some developers who still like to write the full AJAX settings out. Reasons for this might be that they wish to see all the settings to be sure or .get() and $.post() failed to return errors in jQuery < 1.5 which I believe has since been fixed. It is also worth knowing that you can use the Firebug NET.panel to Analyse HTTP Requests for testing, monitoring & debugging AJAX calls. Lets have a look at an example of the ajax jQuery function in action. Further Reading »

Demo

jQuery Function Demo - jQuery4u.com

Demo: Using $.ajax() to load content without reloading the entire page.

HTML content is held in separate files which are inserted below using AJAX. Note that it is also courtesy to show a loading image while the AJAX request is processing. Content 3 has a 2 second delay to simulate the loading image.

Run Demo View Code

Content will appear here.

Download

The download package includes all the inline HTML, CSS, JavaScript, jQuery and images required for the .ajax() function demo so you can try it yourself and change as you please.

The full code listing for all jQuery functions have been now added to GitHub, you can get them there, we are making them work with the latest versions of jQuery!

Code

<!-- Copyright 2011 jQuery4u.com -->
<!DOCTYPE html>
<html>
<title>jQuery Function Demo - jQuery4u.com</title>
<head>
    <script src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
    <script src="http://www.jquery4u.com/scripts/function-demos-script.js"></script>

    <script type="text/javascript">

    var JQFUNCS =
    {
        runFunc:
        {
            /* ------------------------------ ajax Demo ------------------------------ */
            "ajax":
            {
                run: function(id)
                {
                    $('#'+id+' .content1').bind('click', function(e)
                    {
                        e.preventDefault();
                        getContent('/function-demos/functions/ajax/data/content1.html');
                    });

                    $('#'+id+' .content2').bind('click', function(e)
                    {
                        e.preventDefault();
                        getContent('/function-demos/functions/ajax/data/content2.html');
                    });

                    $('#'+id+' .content3').bind('click', function(e)
                    {
                        e.preventDefault();
                        getContent('/function-demos/functions/ajax/data/content3.html');
                    });

                    function getContent(filename)
                    {
                        $.ajax({
                            url: filename,
                            type: 'GET',
                            dataType: 'html',
                            beforeSend: function() {
                                $('#'+id+' .contentarea').html('<img src="/function-demos/functions/ajax/images/loading.gif" />');
                            },
                            success: function(data, textStatus, xhr) {

                                if (filename == '/function-demos/functions/ajax/data/content3.html')
                                {
                                    setTimeout( function() {
                                        $('#'+id+' .contentarea').html(data);
                                    }, 2000);
                                }
                                else
                                {
                                    $('#'+id+' .contentarea').html(data);
                                }
                            },
                            error: function(xhr, textStatus, errorThrown) {
                                $('#'+id+' .contentarea').html(textStatus);
                            }
                        });
                    }

                },

                reset: function(id)
                {
                    $('#'+id+' .contentarea').html('Content will appear here.');
                    $('#'+id).hide();
                }
            }
        }
    }

    </script>

</head>
<body>

<h3>Demo: Using $.ajax() to load content without reloading the entire page.</h3>
<p>HTML content is held in separate files which are inserted below using AJAX. Note that it is also courtesy to show a loading image while the AJAX request is processing. Content 3 has a 2 second delay to simulate the loading image.</p>
<p><a href="#" id="ajax-demobtn" class="demobtn btn actionr">Run Demo</a> <a href="#" id="ajax-codebtn" class="codebtn btn actionr">View Code</a> <a href="#" id="ajax-resetbtn" class="resetbtn btn actionr" style="display: none;">Reset</a></p>
<div class="demoarea" id="ajax">
<div class="contentarea" style="border:1px solid orange;padding:10px;margin-bottom:5px;">Content will appear here.</div>
<button class="content1 btn">Load content 1</button> <button class="content2 btn">Load content 2</button> <button class="content3 btn">Load content 3</button></div>

</body>
</html>
<!-- Copyright 2011 jQuery4u.com -->