0

I am doing an AJAX call in my beforeSubmit() function, as follows:

$('#register-form').on('beforeSubmit', function(event) {
    $.ajax({
        url: url,
        success: function(response) {
            return response.status; // boolean
        }
    });
});

I want the result of the AJAX success function (true or false) to determine the return value of the beforeSubmit() function.

I realise that you can't return within ajax success, I'm also aware a potential solution to this would be to set async: false in my AJAX call, however I know this isn't recommended, so would prefer to try a different solution.

I have tried to implement a "callback" function as detailed in these posts:

ajax return true/false - I have implemented a callback

jQuery: Return data after ajax call success

But I still cannot seem to get it to work.

MAX POWER
  • 5,213
  • 15
  • 89
  • 141
  • what have you done so far following the above given posts? what happens that you decide to say it is not working? – Muhammad Omer Aslam Aug 14 '18 at 23:51
  • if you are thinking that you can continue to submit the form or stop the submission of the form based on returning the ajax `response.status` it wont work, you would have to manually submit the form – Muhammad Omer Aslam Aug 15 '18 at 00:12

1 Answers1

0

I have solved this as follows:

$('#register-form').on('beforeSubmit', function(event) {
    var form = $(this);

    if (!form.hasClass('complete')) {
        $.ajax({
            url: url,
            success: function(response) {
                if (response.status == true) {
                    form.addClass('complete').submit();
                }
            }
        });

        return false;
    }
});

So the beforeSubmit() function only returns false if the form does not have class 'complete'. If it does, it will proceed with default form submission.

MAX POWER
  • 5,213
  • 15
  • 89
  • 141