I am using a PHP script that returns 'y' or 'n' depending on the data entered by the user, which is being passed through the variables uname and pass.
I am using the ajax $.get() method to call the php script.
If I try to output the data within the $.get() method, it works perfectly but gives a problem when I use an if statement to compare the value with 'y' or 'n'.
My code goes like this-
var status;
$('#login').click(function(){
$.get("login.php", { uname: document.getElementById('uname').value, pass: document.getElementById('pass').value } )
.done(function( data ) {
status=data;
alert(status); //This works
});
if(status=='y')
{
alert('yes!'); //This is not working
// window.location.replace("welcome.html");
}
else if(status=='n')
{
alert('no!'); //This is not working
}
});
Any help would be greatly appreciated.
Move your if condition inside ajax due to async nature of ajax:
var status;
$('#login').click(function(){
$.get("login.php", { uname: document.getElementById('uname').value, pass: document.getElementById('pass').value } )
.done(function( data ) {
status=data;
if(status=='y')
{
alert('yes!');
}
else if(status=='n')
{
alert('no!');
}
});
});
This is a typical async problem. You make a request, compare the result that didn't come back yet with some strings, then the response to your request comes - way too late for it to matter. You are too fast with your check. Put your status comparisons inside the done callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With