0

I have the following function:

function sendDocument( objektnummer, id )
{
    var url = $( "#objectdata" ).data( "url-send" );
    var data = {};
    data["objektnummer"]    = objektnummer;
    data["id"]              = parseInt(id);

    var result = false;
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json"
    })
        .done(function(resp){
            console.log("send ajax was successfull");
            result =  true;
        })
        .error(function(resp){
            console.log("no connection");
            result =  false;
        });
    console.log(result);
    return result;
}

in the console I got the positive message "send ajax was successful", but when I print the result on the end of the function to the console, I see that the variable result have the value false.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • 2
    You cannot return values from a function when the Ajax operation is Asynchronous. That function returns long before the `return = true` is set. Pass a callback, or return the Ajax object (which is a jQuery `promise`). – iCollect.it Ltd Sep 03 '14 at 10:09

1 Answers1

0

You cannot return values from a function when the Ajax operation is Asynchronous. That function returns long before the return = true is set. Pass a callback, or return the Ajax object (which is a jQuery promise).

Callback version:

function sendDocument( objektnummer, id, callMeWhenDone )
{
    var url = $( "#objectdata" ).data( "url-send" );
    var data = {};
    data["objektnummer"]    = objektnummer;
    data["id"]              = parseInt(id);

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json"
    })
        .done(function(resp){
            console.log("send ajax was successfull");
            callMeWhenDone(true);
        })
        .error(function(resp){
            console.log("no connection");
            callMeWhenDone(false);
        });
}

Call with a callback:

sendDocument( objektnummer, id, function(success){
      if (success){
          // Do this!
      }
} );

A promise version in this case would look like:

function sendDocument( objektnummer, id )
{
    var url = $( "#objectdata" ).data( "url-send" );
    var data = {};
    data["objektnummer"]    = objektnummer;
    data["id"]              = parseInt(id);

    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json"
    })
        .done(function(resp){
            console.log("send ajax was successfull");
        })
        .error(function(resp){
            console.log("no connection");
        });
}

And would be called like this:

sendDocument( objektnummer, id ).done(function(){
      // Do this!
} ).fail(function(){
      // Something went wrong!
});

With promises, you can register for the events any number of times (so it is considered more flexible than callbacks)

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202