niko
niko

Reputation: 9393

submitting the form without waiting for AJAX response

$('#form1').submit(function () {
    var filal = $('input#l_email').val().length && $('input#l_pswd').val().length;
    if (!(filal)) {
        $("div#login_feed").fadeIn(400);
        return false;
    } else {
        alert('hello')
        $.post('create_login.php', {
            lemail: $('input#email').val(),
            lpswd: $('input#pswd').val()
        }, function (result) {
            if (result == 'sucess') return true;
            else return false;
        });
    }
});

I am unable to find where the bug is. If it enters into if block, it won't submit the form but I do not know what's going wrong. When it enters else block, it alerts hello and automatically submits the form without waiting for the completion of AJAX request. I know the code is creepy with too may return statements but I am new to jQuery style so kindly let me know the way to do it.

Upvotes: 0

Views: 1489

Answers (3)

Kevin B
Kevin B

Reputation: 95023

You cannot return out of an asynchronous callback:

var x = setTimeout(function(){
    return "foobar";
},1000)
console.log(x); // the id of the settimeout instead of "foobar"

The same thing happens with your ajax request.

var foo = (function(){
    $.post("foo.php",function(){
        return "foobar";
    })
})();
console.log(foo); // undefined because your function didn't return anything!!

In your case, you need to stop the default action completely then submit the form after the ajax request.

$('#form1').submit(function (event) {
    event.preventDefault(); // stop default action
    const theform = this;
    const bothFilled = $('#l_email').val().length && $('#l_pswd').val().length;
    if (bothFilled) {
        $.post('create_login.php', {
            lemail: $('#email').val(),
            lpswd: $('#pswd').val()
        }, function (result) {
            if (result === 'success') theform.submit(); // submit form, bypassing jQuery bound submit handler to prevent infinite loop
        });
    } else {    
        $("#login_feed").fadeIn(400);
    }
});

Upvotes: 2

Robert McKee
Robert McKee

Reputation: 21487

$('#form1').submit(function (event) {
    event.preventDefault();
    var filal = $('#l_email').val().length && $('#l_pswd').val().length;
    if (!(filal)) {
        $("div#login_feed").fadeIn(400);
    } else {
        $.post('create_login.php', {
            lemail: $('#email').val(),
            lpswd: $('#pswd').val()
        }, function (result) {
            if (result == 'sucess')
                $('#form1').get().submit();

        });
    }
});

Upvotes: 0

Antoine
Antoine

Reputation: 2807

The submit action send the form by default, you need to stop that with preventDefault();

$('#form1').submit(function (event) {
  event.preventDefault();

Upvotes: 1

Related Questions