0

Im really breaking by head on this one. Ive read a lot about callbacks and know ajax is asynchronous but I cant for the life of me find how to get a value back that I can use later on in a if statement.

$.ajax({
    url: 'http://'+document.domain+'/klanten/updateaddress.php',
    type: 'post',
    data: poststring,
    success: function(result) { 
    console.log("result = "+result);    
    callbacks.add(result);

    }
});

//this doesnt work because result is generated asynchonous. 
if(result == success){
//do something
}

the console.log perfectly shows success or an error I generated in updateaddress.php and I really need to use the if statement to execute some code after it has gotten success or not. Can anyone explain to me how the callback system works in this case?

Thanks!

Snuur
  • 311
  • 1
  • 3
  • 11

1 Answers1

1

Since this is async it could take a some time for this to finish. You need to pass it in a callback that will run later:

$.ajax({
    url: 'http://'+document.domain+'/klanten/updateaddress.php',
    type: 'post',
    data: poststring,
    success: function(result) { 
        console.log("result = "+result);    
        callbacks.add(result);
        if(result == success){
            //do something
        }

    }
});

To explain, we don't know when that if statement will happen, but it def won't happen right away, therefore we tell javascript, run the following when you are ready.

Google javascript callbacks for more info

http://recurial.com/programming/understanding-callback-functions-in-javascript/

MosheK
  • 1,196
  • 1
  • 9
  • 16