I'm writing some form validation code in jQuery. I've noticed something very strange with the following code:
var $form = $('#test-form');
$form.on('submit', function(e) {
e.preventDefault();
validate();
});
function validate() {
console.log('in');
$form.submit();
}
I expected to get the console.log back once and then for the form to submit. Instead I get the console log around 700 times and the form does not submit. This can be seen in this test:
What the hell is going on here?
Use native submit to bypass the jQuery event handler:
function validate() {
console.log('in');
$form.get(0).submit(); // same as document.getElementById("test-form").submit();
}
You have a infinite loop inside your code:
var $form = $('#test-form');
$form.on('submit', function(e) {
e.preventDefault();/*Prevent form validation default event*/
validate();/*Call the function Validate*/
});
function validate() {
console.log('in');/*Log in the console*/
$form.submit();/*Call the default submit event of the form which get you back at line 4, this will go on fore ever.*/
}
you should avoid $form.submit()
inside validate()
as it will cause an infinite loop. validate()
should use the data that the validation return not resubmit the form.
you probably are looking for something like :
function AJAXValidation()
{
var request = $.ajax(
{
url: "Process.php",
type: "POST",
contentType:"application/x-www-form-urlencoded;charset=UTF-8",
data:
{
/*your data*/
}
});
/*call back fonction which is like your validate() function*/
request.done(
function(message)
{
/*Do stuff with message*/
});
}
in this code message could be anything a JSON string, a name, a date, wahtever Process return.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.