JQuery

JQuery AJAX

In this tutorial I will talk you through how to accomplish AJAX in JQuery. I have made a normal JavaScript version of this tutorial, however, I find JQuery a much nicer library for AJAX functions.

First thing you need is JQuery. You can add JQuery to your document by simply adding this line of code to your element:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>

After you have added this you are ready to learn JQuery AJAX! The first thing we will do is look at a very basic function for it:

          //the dataString is the variable which holds information needed to be parsed to the sever-side script. This variable holds information in the same form as a $_GET request
	  var dataString = 'title='+ titleFin + '&description=' + descFin + '&tags=' + tagsFin + '&rate=' + rateFin + '&rate1=' + rate1Fin + '&Nud=' + sexFin + '&id=' + uploadID + '&upID=' + upID;
	  $.ajax({
            //this dictates the method to be used, either GET or POST
	    type: "POST",
            //the url of the page to be polled
	    url: "ajax/jxSV_VID.php",
            //you now add the dataString you made earlier to the data part of the AJAX request
	    data: dataString,
            //if the AJAX poll was successful it will run the following function(s)
	    success: function(msg) {
		    if(!msg) return;

		    var response;
                    //you can eval the response (msg) to be able to read in JSON arrays. This is particularly useful if you wish to create error messages etc.
		    eval("response = "+msg);
			
		    if(!response) return;
 
                    //As you can see i have presented you with a basic post-processing function which accesses the JSON string I just eval-ed and assesses whether or not the script succeeded.
		    var DivInQ = "#eC_Err"+uploadID;
			var Error = parseInt(response['ErrorCode']);
			
			if(Error == 0){
				$(DivInQ).css({"display" : "block", "color" : "green", "text-align" : "center"});
		    	$(DivInQ).html("<span><b>Success:</b> "+response['Message']+"</span>");
			}else{
				$(DivInQ).css({"display" : "block", "color" : "red", "text-align" : "center"});
		    	$(DivInQ).html("<span><b>Error:</b> "+response['Message']+"</span>");
			}
	  	}
	  });

This is just a basic script but you now see how AJAX is done within JQuery, it really is that simple :). Now the reason why I love JQuery is that there is more than just success function available to you. In fact there is a function for nearly every single part of an AJAX request you could ever imagine, way more than normal JavaScript. You can see the full Ajax documentation here.

Now let us have a look at a real website example of how this AJAX function can be used:

function do_ajax(method, url, dataString){	  

	$.ajax({
	    type: method,
	    url: url,
	    data: dataString,
            //error is an extra function which allows us to detect an error such as 404. The three parameters you see can be used to detect what kind of error is being thrown
            //Here however I am just throwing a message box with a generic AJAX error.
	    error: function(xhr, ajaxOptions, thrownError){
    		ShowMessageBox("Ajax Error", "<p>The request could not be completed for an unkown reason. Please check your internet connection and make sure it is connected.</p>"+
    									 "<p>If this problem persists please contact either a moderator or an administrator.</p>", OK_ONLY);
		},
	    success: function(callback) {
		    if(!callback) return;

		    var response;
		    eval("response = "+callback);
		    return response;
		    
		}

	});

}

As you can see in the real life example error functions would be added to aid in detecting possible flaws within JQuery AJAX functions. This is the typical real world example you will find, and this function would normally be attached to a loading div that is binded to the ajaxStart() as such:

 $("#loading").ajaxStart(function(){
   $(this).show();
 });

You can always go one step further. Imagine you are AJAX paging and wish to display comments:

 $("#feeds").load("feeds.php", {limit: 25}, function(){
   alert("The last 25 entries in the feed have been loaded");
 });

This is an example taken from the JQuery documentation, however, I will be showing a example of this in my AJAX paging post when I write it.

So I have shown to you that, with JQuery, the possibilities with AJAX are infinite. The sky is the limit and you can make a brilliant AJAX app in minutes with the functions provided by JQuery. Just remember that in IE 8 you will have to break the compatibility button in order to get JQuery to work. Enjoy 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s