Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of JQuery ajax call

I want this function to return wether or not the ajax call was succesful or not. Is there any way I can do this? My code below doesn't do this.

function myFunction(data) {
var result = false;
$.ajax({
    type: "POST",
        contentType: "application/json",
        dataType: "json",
        url: "url",
        data: data,
        error: function(data){
             result = false;
             return false;
        },
        success: function(data){
            result = true;
            return true;
        }
     });
     return result;
}
like image 490
hansi Avatar asked Feb 21 '23 08:02

hansi


1 Answers

Unfortunately, you cannot return values to functions that wrap asynchronous callbacks. Instead, your success callback from the AJAX request will handoff the data and control to another function. I've demonstrated this concept below:

Definition for myFunction:

// I added a second parameter called "callback", which takes a function
 // as a first class object
function myFunction(data, callback) {
    var result = false;
    $.ajax({
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        url: "url",
        data: data,
        error: function(data){
            result = false;

            // invoke the callback function here
            if(callback != null)  {
                callback(result);
            }

            // this would return to the error handler, which does nothing
            //return false;
        },
        success: function(data){
            result = true;

            // invoke your callback function here
            if(callback != null) {
                callback(result);                
            }

            // this would actually return to the success handler, which does
              // nothing as it doesn't assign the value to anything
            // return true;
        }
     });

     // return result; // result would be false here still
}

callback function definition:

// this is the definition for the function that takes the data from your
 // AJAX success handler
function processData(result) {

    // do stuff with the result here

}

invoke your myFunction:

var data = { key: "value" }; /* some object you're passing in */

// pass in both the data as well as the processData function object
 // in JavaScript, functions can be passed into parameters as arguments!
myFunction(data, processData);
like image 135
jmort253 Avatar answered Mar 06 '23 00:03

jmort253