Javascript AJAX function returns undefined instead of true / false

I have a function that issues an AJAX call (via jQuery). In the section complete

, I have a function that says:

complete: function(XMLHttpRequest, textStatus)
{
    if(textStatus == "success")
    {
        return(true);
    }
    else
    {
        return(false);
    }
}

      

However, if I call it like this:

if(callajax())
{
    //  Do something
}
else
{
    // Something else
}

      

The first one is never called.

If I put alert(textStatus)

in a function complete

, I believe, but not until this function returns undefined

.

Can I pass a callback function to my method callajax()

? How:

callajax(function(){// success}, function(){// error}, function(){// complete});

+2


a source to share


1 answer


complete

- callback function. It will be called by the Ajax object - asynchronously! - when the operation is completed. You have no way to catch the result of the callback, only the Ajax object can do that.

Your function callajax()

- you are not showing this function, but I am assuming that it is just making an Ajax call - cannot return the call result (= response headers and body), since the call is not finished yet when you exit the function callajax()

.



Update: It's also possible to make synchronous AJAX calls. Thanks @Andris for this. In jQuery, you need to set the option async

to false

: Docs here . However, even those who have the ability to use standard callback functions, so your desired return false

or method true

may still not work.

+7


a source







All Articles