user3142695
user3142695

Reputation: 17332

preventDefault() in AJAX doesn't work

Why doesn't event.preventDefault(); work in this AJAX-setting?

$( "#formID" ).submit(function( event ) {
    $.ajax({
        url: "ajax.php",
        type: "GET",
        data: { 'data': 'anything' },
        dataType: "json"
    })
    .done(function( json ) {
        if (!json.result) { 
            event.preventDefault();
        }
    });
});

UPDATE:

On submitting a form I want to check via Ajax if a condition is true or false. Depending on that the submit should be prevented (if result of the AJAX call is false).

Is this possible?

Upvotes: 0

Views: 2013

Answers (3)

HDT
HDT

Reputation: 2047

use return false; to prevent default submit. If you want to wait data return use async: false

$( "#formID" ).submit(function( event ) {
    $.ajax({
        url: "ajax.php",
        type: "GET",
        data: { 'data': 'anything' },
        dataType: "json",
        async: false
    })
    .done(function( json ) {
        if (!json.result) { 
            event.preventDefault();
        }
    });
   return false;
});

Upvotes: 1

svjn
svjn

Reputation: 914

event.preventDefault will prevent any specified event prior to form submission. In your case, you call preventDefault inside callback function of Ajax call, which is an asynchronous call where your form would be submitted before the callback function executes. So it doesn't make any sense where you placed it.

Place it out of Ajax call (prior to ajax call) as follows,

$( "#formID" ).submit(function( event ) {
    event.preventDefault();
    $.ajax({
        url: "ajax.php",
        type: "GET",
        data: { 'data': 'anything' },
        dataType: "json"
    })
.
.

and call the form submit inside ajax callback method if your result is satisfied.

.done(function( json ) {
        if (json.result) { 
            // Do form submit here.
        }
    });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

since ajax is asynchronous the form will get submitted before the ajax is completed

$("#formID").submit(function (event) {
    //prevent the form submit by default
    event.preventDefault();
    var form = this;
    $.ajax({
        url: "ajax.php",
        type: "GET",
        data: {
            'data': 'anything'
        },
        dataType: "json"
    })
        .done(function (json) {
        if (json.result) {
            //if ajax is success submit the form
            form.submit()
        }
    });
});

Upvotes: 2

Related Questions