An analysis on the onsubmit of using AJAX to return false when validating forms _jquery

Source: Internet
Author: User
Copy Code code as follows:

/**
* Form submission Verification
**/
function OnSubmit () {
if ($ (' #name '). Val (). length<2) {
Alert ("Name please not less than two characters");
return false;
}
var t = new Date (). GetTime ();
$.ajax ({
Type: "POST",
URL: "/users/checkrepeat/",
Data: "Name=" + $ (' #name '). Val () + "&time=" + t,
Success:function (res) {
if (res = = ' exists ') {
Alert ("Name already exists, please modify.");
return false;
}
}
});
}

Problem Reason:
1. The function of return false in Ajax is not the same as onsubmit ();
2. In the case of Ajax execution, the default setting value of Async is true, which is asynchronous, that is, when Ajax sends a request, the foreground will continue to execute the script behind the AJAX block while the server is waiting for it to return. It is not until the server side returns the correct results that the success is executed, that is, two threads are executed at this time, and the Ajax block makes the script (another thread) after the request followed by a thread and an AJAX block.

Modified code:
Copy Code code as follows:

/**
* Form submission Verification
**/
function OnSubmit () {
if ($ (' #name '). Val (). length<2) {
Alert ("Name please not less than two characters");
return false;
}
var flag = true;
var t = new Date (). GetTime ();
$.ajax ({
Type: "POST",
Async:false,//Set sync mode
Cache:false,
URL: "/users/checkrepeat/",
Data: "Name=" + $ (' #name '). Val () + "&time=" + t,
Success:function (res) {
if (res = = ' exists ') {
Alert ("Name already exists, please modify.");
Flag = false;
}
}
});
if (!flag)
return false;
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.