Tutorial :jQuery Ajax fallback return



Question:

I have a JavaScript function inside which I use jQuery .post, and I wanted to return a boolean in the fallback:

function is_available() {      $.post('ajax', {          action: 'mail'      }, function(data) {          if ($.trim(data) == 'NO_ERROR') {              return true;          } else {              return false;          }      });  }  

but the function returns undefinied. How could I return that boolean?


Solution:1

Since those return statements you currently have don't run until later, you need to call any code that relies on the data from the callback, for example:

function check_available() {    $.post('ajax', {      action: 'mail'    }, function(data) {      myNextFunction($.trim(data) == 'NO_ERROR');    });  }  function myNextFunction(isAvailable) {    //do something, this runs after the AJAX request completes the check  }  

So instead of treating is synchronosuly with a return statement, treat the code path as asynchronous, and kickoff whatever code needs that "is available" value from the callback of $.post(), it'll execute when the server request comes back and that boolean you need is ready to use.

Currently it's returning undefined because that callback function happens later (after your current code trying to use the value).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »