0

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!

Javier Villanueva
  • 3,886
  • 13
  • 48
  • 80
  • 5
    Welcome to the wonderful world of **async**! You can't do that. – SLaks Mar 13 '12 at 23:29
  • possible duplicate of [jQuery: Return data after ajax call success](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success) – Felix Kling Mar 13 '12 at 23:31
  • FYI, if you put your code inside the `ready` handler, it already gets `jQuery` passed as first argument, so you can simply remove the immediate function call: `jQuery(function($) { ... code here ...});` – Felix Kling Mar 13 '12 at 23:33

2 Answers2

6

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
  }
});
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

you can put async:false parameter to ajax request then you can control future responce and send back the result to parent. see following main lines enclosed within ***
add: function (e, data) {

    //before upload file check server has that file already uploaded
      ***var flag=false;***
      $.ajax(
            {
                type: "POST",
                dataType:'json',
                url:"xyz.jsp",
                ***async:false,***
                data:{  
                         filename : upload_filename,
                         docname : upload_docname,
                         userid : upload_userid,
                    },
                success:function(data)
                {
                    ***flag=true;***
                },
                error:function(request,errorType,errorMessage) 
                {
                    alert ('error - '+errorType+'with message - '+errorMessage);
                }
        });

       ***return flag;***

        }
Arjun Patil
  • 111
  • 9