javiervd javiervd - 7 months ago 18
Javascript Question

How to return a value inside AJAX function to parent in javascript?

I'm trying to return true or false to a function depending on the response of an AJAX function inside of it but I'm not sure how should I do it.

(function($) {
$('#example').ajaxForm({
beforeSubmit : function(arr, $form, options) {

var jsonStuff = JSON.stringify({ stuff: 'test' });

$.post('/echo/json/', { json: jsonStuff }, function(resp) {

if (resp.stuff !== $('#test').val()) {
// Cancel form submittion
alert('Need to type "test"');
return false; // This doesn't work
}

}, 'json');

},
success : function() {
alert('Form sent!');
}
});
})(jQuery);​


I made a fiddle to illustrate this better:

http://jsfiddle.net/vengiss/3W5qe/

I'm using jQuery and the Malsup's Ajax Form plugin but I believe this behavior is independent of the plugin, I just need to
return false
to the
beforeSubmit
function depending on the
POST
request so the form doesn't get submitted every time. Could anyone point me in the right direction?

Thanks in advance!

Answer

This is not possible to do when dealing with async functions. The function which calls post will return immediately while the ajax call back will return at some point in the future. It's not possible to return a future result from the present.

Instead what you need to do is pass a callback to the original function. This function will eventually be called with the result of the ajax call

var makePostCall = function(callback) {
  $.post('/echo/json/', { json: jsonStuff }, function(resp) {
    if (resp.stuff !== $('#test').val()) { 
      // Cancel form submittion
      alert('Need to type "test"');
      callback(false);
    } else { 
      callback(true);
    }}, 'json');
};

Then switch the code which expected a prompt response from makePostCall to using a callback instead.

// Synchronous version 
if (makePostCall()) { 
  // True code 
} else {
  // false code
}

// Async version
makePostCall(function (result) {
  if (result) {
    // True code
  } else {
    // False code
  }
});
Comments