I’m having an issue with Javascript executing things in an order that doesn’t make sense to me.
What is happening is the following
var bValid = false;
alert(bValid + " 1");
if(validateForm() == TRUE)
{
$.get("submit_manageUsers.php",
{action: sendAct, userID: userID},
function(responseText)
{
if(responseText == "GOOD")
{
alert("Update Successful");
bValid = true;
alert(bValid + " 2");
}
else
{
alert(responseText + "\n Update Unsuccessful");
bValid = false;
}
},
"html"
);
bvalid = true;
alert(bValid + " 3");
}
alert(bValid + " 4");
if(bValid == true)
{
//do something
}
alert(bValid + " 5");
EDIT: added a bit more of what is actually happening in case it helps, probably will knowing how I do things!
The output from the above code looks like this:
false 1
false 2
false 4
false 5
true 3.
The problem here is that the if(bValid == true) is being executed before the if(validateForm() == TRUE) so this means bValid is always false.
Why is that part of the code executing before the other part?
Any help on this is greatly appreciated!
Javascript is case sensitive. validateForm() returns a bool right? So its either true or false. TRUE is not the same as true.
I would even go one step further and use strict equals:
Also, bvalid is not the same as bValid.
In the future I would suggest utilizing one of the numerous javascript tools out there to help find syntax errors (such as jsfiddle, jslint, jsbin, etc.). We all make mistakes, and sometimes these little simple details cause big headaches. There is not a compiler crutch (like I use everyday with C#) for javascript although YUI and Google have syntax checking tools to help.
Google – http://code.google.com/closure/
Yahoo! – http://developer.yahoo.com/yui/
After more information was provided in the original question –
You are making an asynchronous call to your PHP page that may take 1 second or 30 seconds.
http://api.jquery.com/jQuery.ajax/
JQuery ajax (which powers the .get function) is asynchronous by default. However, you can override this and make synchronous.