Reputation: 35
I am fairly new to AJAX. I am trying to get a simple login script to work. This is using jQuery 1.6.4. In the AJAX below, when the user clicks a button, it sends the email address and password to login.php.
That all seems to work fine. The trouble is with the success function. When the email and password are correct, it should return true. It should return false when it does not work. Using Firebug, I see that it works with console.log. It also works correctly if I write alert(response);. However, the conditional always evaluates to false even when response is equal to true. I've tried both if(response=="true")
and if(response==="true")
, putting the variable outside the function, and a few other things without success. Would anyone have any ideas on how to fix this?
Thank you for any help or ideas, Jason.
AJAX:
$("#firstpage").live('pageinit', function (evt) {
$('#button').click(function(){
var $form = $('#login'),
$inputs = $form.find("input"),
serializedData = $form.serialize();
$.ajax({
type: 'POST',
url: 'php/login.php',
data: serializedData,
success: function(response){
console.log("Response: "+response);
if(response=="true")
{
$('#firstpage #wrong').text("Login script is working");
} else {
$('#firstpage #wrong').text("Your email and password combination did not match.");
}
},
dataType: 'json'
});
});
});
If it helps, this is my login.php script.
$email = $_POST['email'];
$password = $_POST['password'];
require_once("DB.php");
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
$query = "SELECT * FROM member WHERE email='$email' AND password='".md5($_POST['password'])."'";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows>0){
$output = true;
} else {
$output = false;
}
echo json_encode($output);
Upvotes: 3
Views: 3699
Reputation: 4003
The response is an object because you have "dataType: 'json'". jQuery will try and convert the responseText to JSON. If you need to check the data the server returned, try using
if (response === true) {
}
or simply
if (response) {
}
or just have jQuery return the string by removing the datatype: 'json'
Upvotes: 1
Reputation: 2311
Don't use quotations with an exactly-equals sign ===
. Use
if (response === true)
Because your PHP script returns true
, not "true"
.
I'm not avid with PHP, but try removing the quotes around true.
Upvotes: 0