0

I am having the bellow function . Here i want to return ajax success from user defined function . How to do this

alert(Ajaxcall(id_array,"del"));

function Ajaxcall(id_array,type){
            $.ajax({
                    type: "POST",
                    url: "serverpage.php",
                    cache:false,
                    data: ({id:id_array,type:type}),
                    success: function(msg){

                   return msg; //this returns nothing

                    }
            }); 

            alert(msg); // this one undefined

}

thanks

Gowri
  • 16,587
  • 26
  • 100
  • 160

2 Answers2

3

The "a" in "ajax" stands for "asynchronous" ("Asynchronous JavaScript And XML", although these days most people use it with JSON rather than XML).

So your Ajaxcall function returns before the ajax call completes, which is why you can't return the message as a return value.

The usual thing to do is to pass in a callback instead:

Ajaxcall(id_array,"del", functon(msg) {
    alert(msg);
});

function Ajaxcall(id_array,type, callback){
            $.ajax({
                    type: "POST",
                    url: "serverpage.php",
                    cache:false,
                    data: ({id:id_array,type:type}),
                    success: function(msg){

                        callback(msg);

                    }
            }); 
}

It's surprisingly easy with JavaScript, because JavaScript's functions are closures and can be defined inline. So for instance, suppose you wanted to do this:

function foo() {
    var ajaxStuff, localData;

    localData = doSomething();
    ajaxStuff = getAjaxStuff();
    doSomethingElse(ajaxStuff);
    doAnotherThing(localData);
}

you can literally rewrite that asynchronously like this:

function foo() {
    var localData;

    localData = doSomething();
    getAjaxStuff(function(ajaxStuff) {
        doSomethingElse(ajaxStuff);
        doAnotherThing(localData);
    });
}

I should note that it's possible to make an ajax call synchronous. In jQuery, you do that by passing the async option in (setting it false). But it's a very bad idea. Synchronous ajax calls lock up the UI of most browsers in a very user-unfriendly fashion. Instead, restructure your code slightly as above.

But just for completeness:

alert(Ajaxcall(id_array,"del"));

function Ajaxcall(id_array,type){
    var returnValue;
            $.ajax({
                    type: "POST",
                    url: "serverpage.php",
                    cache:false,
                    async: false,        // <== Synchronous request, very bad idea
                    data: ({id:id_array,type:type}),
                    success: function(msg){

                        returnValue = msg;

                    }
            }); 
    return returnValue;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • ca i use msg outside that callback Ajaxcall(id_array,"del",function(msg){ }); alert(msg); like this – Gowri Mar 28 '11 at 07:27
  • @gowri, no, `msg` does not exist outside the callback. – David Tang Mar 28 '11 at 07:31
  • @gowri: You could assign it to a variable you declared in the containing scope, but again, you have to think asynchronously -- will it be set at the time you use it? That's why I gave the example of how easy it is in JavaScript to modify step-by-step logic to handle asynchronousness. At the point of an async operation, start a new function and move everything that should follow *into* that function. You can even nest these. – T.J. Crowder Mar 28 '11 at 07:32
  • thank you T.J .. not yet understand asynchronous and synchronous stuff. but i'll learn ASAP – Gowri Mar 28 '11 at 07:38
  • @gowri: No worries, glad that helped. Once you get your head around it, it's easy. [Here's an example](http://jsbin.com/izobi3) that uses three separate ajax calls, each nested, and demonstrates how each of the callbacks is a closure over a local variable in the function where they're defined. (If you're not too sure about closures, read the [article](http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html) linked in the answer.) Best, – T.J. Crowder Mar 28 '11 at 07:41
1

JQuery has a number of global Ajax event handlers, including $.ajaxComplete() and $.ajaxSuccess() (ref: http://api.jquery.com/ajaxSuccess/).

The code can be attached to any DOM element and looks like this:

/* Gets called when all request completes successfully */
      $("#myElement").ajaxSuccess(function(event,request,settings){
          $(this).html("<h4>Successful ajax request</h4>");
      });

This code will execute whenever any successful Ajax call is completed.

Phil.Wheeler
  • 16,748
  • 10
  • 99
  • 155