thecfguy

A Unique Developer

Different way to pass additional data to jQuery.ajax callback function

Now a days we can not imagine web application with AJAX and jQuery make stuff lot easier to us. We normally need to use ajax call to update web content asyncronously. $.ajax is really simple to use, well I haven't write this post to advertise $.ajax but to explain how we can pass our custom arguments to its callback function.

$.ajax callback function have three default parameter 1. Content 2.Status 3. HTTPResponse object and in most of the case this are enough information in case you want to alert user or display message on particular dom object.

Below is how we implement.

But what if I want to pass some additional parameter other than default one to customize my output or something that I want to use on my callback function. Well, this can be easily done by creating seperate function and call custom function from succes. I may look like below.

In above sample we just pass "div1" as argument but what if I have similar 8 div elements which display messages return through ajax call through loop. For every request I want to display response in different div element and may be my code will look like below. 

Oh, I can't find any response on my web page. Well, because variable 'i' passed as second argument of showMessage assuming that each iteraction value of i will pass in showMessage but forget that we are on asyncrhonous call and before callBack function call loop may finish with all iterations and value of i will be 4 ( as my condition is i<=3) and for all callback function showMessage function call with value 4 in second argument.

So, how to pass each iteration value of i in call back function? By writing function which take argument but return function as parameter 'success' take function pointer.

Just like below.

Voila, It works....

We just want to make sure value of 'i' pass at the time of iteration not on callback, function showMessage take single argument where we pass iteration value of i and return function. In statement "success:showMessage(i)", showMessage(i) is function call will pass value of i at the time of itegration.