Home /JavaScript/jQuery with Ajax

jQuery with Ajax

Your life just got much easier my friend. A quality AJAX script that does a simple GET or POST is massive. With jQuery, you can make that much more manageable. I should go ahead and tell you upfront that AJAX is a technology that allows you to send requests to a server without ever reloading the page. Another important note is jQuery's ajax method is not the only ajax that is possible with jQuery.

Important AJAX Methods

.load(url,data,callback)

loads data from selected object

.ajax(settings)

loads data into an XMLHttpRequest object

Load Example

<div id="firstLoadDiv">I am special</div>
<div id="secondLoadDiv">I am not</div>
<input id='buttonLoadId' name="buttonLoad" type="button" value="Do AJAX!"/>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#buttonLoadId").click(function() {
        $('#secondLoadDiv').load(window.location + ' #firstLoadDiv'); //notice the div id reference
    });
</script>

We are actually talking to ourselves on this one. We use the load() method to talk to the jquery-ajax.php file. We go on to inquire in even more detail. We use the div id #firstLoadDiv right after our file reference to get what the contents of that div. Now, we move onto the awesome ajax() method.

Ajax Example

PHP File

<?php
    echo "We win!";
?>

HTML File

<div id="firstAjaxDiv">Default Text</div>
<input id='buttonOneId' name="buttonOne" type="button" value="Do AJAX!"/>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#buttonOneId").click(function() {
        url = ('ajaxTest.php');
        $.ajax({
            url: url,
            success: function(data) {
                if(data != "") {
                    $('#firstAjaxDiv').html(data);
                }
            },
            error: function() {
                $('#firstAjaxDiv').html('It failed…');
            }
        });
    });
</script>

It is somewhat similar to the load() method, but it has a much better layout. We set the url to another page called ajaxTest.php. Then we have two properties that have functions in them. The success property or setting has a function that sets our div firstAjaxDiv's html to the data we receive from our request to the url. Granted, .html is not the best method, but it does get the job done. Second, we have another property error that has a function that tells us if our request went through successfully.

That is some pretty advanced stuff you just did. Take a break you earned it. As always, this is just to better your understanding. You can check out jQuery's AJAX Functions for a full list of the JQuery AJAX methods.