AJAX call inside the onsubmit of a form submits the form despite return false

1.3k views Asked by At

I have form which I will use only for an ajax call. I make the ajax call from onsubmit to be able to use the auto-check for required fields. Even though I return false onsubmit, form submits. And I comment out the statement which makes the ajax call, form does not submit. I gave the from I use below. Why can't I prevent form submission.

<form action="" method="post" onsubmit="ajaxReq (); return false;">
    <input type="hidden" name="type" value='something'>
    <input type="text" name="testText" required>
    <input type="submit" value="AJAX_TEST">
</form>

ajaxReq function is given below

//I will be using the data from the form inside data as the data of the ajax call
//Currently data in the form is ignored
function ajaxReq() {
    var ajaxSettings = {
        'url' : '',
        'async' : false,
        'type' : 'POST',
        'data' : {
            'type' : 'SOME_TYPE'
        },
        'success' : function(data) {
            data = JSON.parse(data);

            //emptying this part did not change the result
            //will be using data here

        }
    };

    $.ajax(ajaxSettings);

    return false;

}
1

There are 1 answers

0
evilunix On

Give your form an ID e.g. id="myform" then:

$('#myform').submit(function(e) {
  e.preventDefault();
  ajaxReq();
});