I have a form that accepts numeric input from the user. Upon form submission, a JS function is called to check the form status (if parameters are ok, etc.). One of its actions is to initiate a AJAX request to receive two values depending on its parameters (that are read from the form). So, I have a function called CheckForm() that runs on form submission and inside it, I have a block that initiates the AJAX request:
var error = 0;
function CheckForm() { // run on form submit
var items = $('myitems');
if (items != undefined || items != null) {
items.each(function() {
if (!isNaN($(this).val())) { // check for number
$.get('myurl', {
// parameters
},
function(data) {
if (data != "0") {
if (condition) error = 1;
}
});
}
if (error == 1) return false;
}); // end each function
if (error == 1) {
alert("You have made an error.");
error = 0;
return false;
}
}
return true;
}
I have also declared a global variable (error) to check if something wrong has happened during the check. myitems is a collection of html elements that the check runs on. So, this function is bind to the form submit click event and is run upon submission.
The question: This does not work. The alert is displayed and the browser page is instantly refreshed (form submitted) without the user clicking on the OK button first.
Is there another way to implement this?
First of all when you use a selector in jQuery the result will never be null or undefined so you can just do :
Second you have to realize you are making asynchronous calls (AJAX), which means the function
CheckFormmay return before even one of thegetcalls has finished.