0

Is there anyway to run an ajax script and have it get a response before running a form POST.

I don't want to post the main form via ajax. I just want it to work whereas when the user hits submit I want ajax to make a call and check a value then when the response comes back then the form will POST via the browser if the response is successful.

Thanks!

4 Answers 4

2

you need to intercept the submit event with preventDefault(), then make your ajax call and decide if you should submit the form or not (either traditional POST, or another ajax call)

sample code:

$('.form-selector').on('submit', function(e) {
    e.preventDefault();

    $.ajax({
        // some call you want to make
    }).done(function() {
        e.target.submit(); // this submits the form without generating the event again
    }).fail(function() {
        // validation failed, do someting here
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Why do not you try two Ajax call. On success of first ajax call you can POST your data.

So here I mean to say do validation on first Ajax call call and on Success of it do another Ajax call and POST your data to server.

Comments

0
var ajax=false; // form has not been submitted, AJAX not responded
$("form").submit( function(e){
    if ( ajax == true ) return true; // if AJAX response, process form normally

    // if no AJAX response, prevent form from submitting
    e.preventDefault();

    // talk to server
    $.ajax({
        ....,
        success: function(){
            // AJAX successful! change value of variable, and submit form
            ajax = true;
            $("form").trigger("submit");
        })
    });

    return false;
});

Comments

-1

Use onSubmit method of your element, as in <form .... onSubmit="fetchData()">

Now, make your own function:

function fetchData(){
  // send your ajax data and validate.
  return true; // true or false depending on what you validated
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.