I am using the jQuery post method to create a record in MySQL. When I evaluate the output of the PHP with ==
, all three conditionals work properly. However, when I use ===
, the first two conditionals return false
. How do I pass the correct data type to Javascript from PHP?
jQuery:
$("#form").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('inc/process_form.php', $("#form").serialize(), function(data) {
//alert(data);
if (data == 1) {
$('#results').html("Success");
} else if (data == 2) {
$('#results').html("No Success");
} else {
$('#results').html(data);
}
});
}
});
This is the PHP (which I've truncated to only show the execute conditional):
$value = $stmt->execute();
if ($value === TRUE) {
echo 1; //success
} else {
echo 2; //failure
}
try this:
if(parseInt(data) === 1){
The problem is the return variable data
is a string, you can't do anything (as far as I know) from PHP to return it as a integer.
As the comment by Marc Costello suggested, this makes the ===
useless since you are forcing both sides to be integer, so data == 1
is better in this case.
I never needed something like this but if you really have to you can simply cast it using +data
:
data = +data;
if (data === 1) {
$('#results').html("Success");
} else if (data === 2) {
$('#results').html("No Success");
}
In this case you can pass boolean value instead of 0 or 1 i.e true or false from php