1

I’m using jQuery validate plugin that has a callback submitHandler. In that callback if it returns false, it aborts the submit and if it returns true it submits using the post method.

  $("#collection_form").validate({

    submitHandler: function(form) {

        pre_ajax_submit(function (pre_ajax_return) {

            if (pre_ajax_return == 'non_ajax') {
                //something
            } else {
                //other
            }
        });
    }
});

So my question is: I have a function in the callback pre_ajax_submit(). How can I have a function return true or false in the main callback. I want to achieve the same result as this:

$("#collection_form").validate({

    submitHandler: function(form) {
        return true;
    }
});
nem035
  • 34,790
  • 6
  • 87
  • 99
xfloys2112
  • 605
  • 1
  • 5
  • 13
  • 1
    What does `pre_ajax_submit()` bring to the party? – Roamer-1888 Jan 26 '17 at 03:53
  • It's another callback from ajax call, that should bring true or false which needs to go to the submitHandler, but I do not know how to make that happen – xfloys2112 Jan 26 '17 at 04:06
  • 1
    is `pre_ajax_submit` asynchronous at all? If so, you have no chance at all. you'll need to post the code for `pre_ajax_submit` for a complete answer – Jaromanda X Jan 26 '17 at 04:12
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – nem035 Jan 26 '17 at 04:23
  • Maybe you want a return value both from sync (`pre_ajax_return == 'non_ajax`) and async cases? – Simone Sanfratello Jan 26 '17 at 04:42

1 Answers1

0

Simply reverse the order of execution. Validate the form after the pre-AJAX task completes:

pre_ajax_submit(function (pre_ajax_return) {
    if (pre_ajax_return == 'non_ajax') {
        //something
    } else {
        //other
    }

    $("#collection_form").validate({
        submitHandler: function(form) {
            return true;
        }
    });
});

I'm guessing you might have lots of other things happening in your code. You should consider using Promises:

var whenPreAJAXFinished = new Promise(function(resolve, reject){
    pre_ajax_submit(function (pre_ajax_return) {
        if (pre_ajax_return == 'non_ajax') {
            //something
        } else {
            //other
        }
        resolve()
    })
})

whenPreAJAXFinished.then(function(){
    $("#collection_form").validate({
        submitHandler: function(form) {
            return true;
        }
    });
});
darrylyeo
  • 3,103
  • 20
  • 30