Javascript not working with php
I am using a PHP script that returns "y" or "n" depending on user input, which is passed through the variables uname
and pass
. I am using ajax method $.get()
to call PHP script.
If I try to output the data in the method $.get()
, it works fine, but gives a problem when I use an if statement to compare a value with "y" or "n".
My code looks 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.
source to share
Move the condition if
inside ajax due to the asynchronous 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!');
}
});
});
source to share
since ajax is asynchronous by the time the code enters the conditional statuses, the request code may not be returned , so the var status may not have been initialized yet . Try to put conditional statuses inside the executed function, for example:
$('#login').click(function(){
$.get("login.php", { uname: document.getElementById('uname').value, pass: document.getElementById('pass').value } )
.done(function( data ) {
if(data =='y')
{
alert('yes!');
// window.location.replace("welcome.html");
}
else if(data =='n')
{
alert('no!');
}
});
I think this should do the trick;) ... for further clarification you can visit the jQuery ajax api documentation: http://api.jquery.com/jquery.ajax/
source to share