mowgli mowgli - 7 months ago 10
Javascript Question

Submit a form generated by jquery

The login form on my site is shown using an overlay/modal with jquery-modal (http://kylefox.ca/jquery-modal/examples/)

I'm using ajax + php to validate the form. If validation passes, the form should be submitted.

I can halt the submit for validation (using return false), and the validation itself is working fine. But I don't know how to submit the form

I have tried many naive variations: return true, $theform.submit(), $("body").unbind("#myloginform") and more.. but so far no luck

$("body").on("submit", "#myloginform", function() {

$theform = $(this);

$.ajax({
url: "login_check.php",
type: "POST",
cache: false,
timeout: 9000,
data: $theform.serialize(),
dataType: "json",
success: function(data) {
if (data) {
if (data.status == "ok") {
alert("success! now the form can be submitted");
// SUBMIT THE FORM (instead of the alert)
} else {
$("body #loginstatus").html(data.status);
}
} else {
alert("Error bla bla.");
}
},
error: function(e) {
alert("Error (ajax) bla bla.");
}
});

return false;

});

Answer

To submit the FORM, you can call js native submit method:

document.getElementById('myloginform').submit();

See variants:

$('#myloginform')[0].submit();
$('#myloginform').get(0).submit();

An other way would be to set context option of ajax to this:

$.ajax({
     context: this,
     ...,
});

And then in success callback, submit FORM using:

this.submit();

EDIT: i see you are already using a variable reference, so in your case, you can use too:

$theform[0].submit();

All these snippets won't trigger jQuery submit handler, avoiding a circular reference error.

Comments