Reputation: 261
I have a switch statement which return true or false and and an if and else statement I then use it to make some more validation.
Because the value is getting send on an input field using ajax. I want PHP to return true or false.
I have try this using JSON and I use an alert to test what I am getting back and its just a lot of html.
$a = isset($_POST['ccode']) ? $_POST['ccode'] : NULL;
function isValid($Code) {
switch ($Code){
case "123":
case "45545":
return true;
default:
return false;
}
}
if(isValid($a)) {
$correct = "correct";
echo json_decode($correct);
}
else {
$incorrect = "incorrect";
echo json_decode($incorrect);
}
AJAX
$('#ccode').blur(function() {
var code = $(this).val();
$.ajax({
type:'POST',
url: 'index.php',
dataType: 'json',
data:{
ccode:code
},
success: function(data) {
alert(data);
}
});
when you see alert(data) I am going to replace it with
if (data == false) {
//do this
}
});
My code doesn't return true or false from php and in the alert it just output a lot of html from my index page.
What have I done wrong?
Upvotes: 1
Views: 7915
Reputation: 965
Replace in your PHP
echo json_decode($incorrect);
to
echo json_encode(array("error"=>false, "message"=>$incorrect));
And then in javascript parse this json.
and do this way in jquery
if (data.error == false) {
//do this
}
Upvotes: 0
Reputation: 2397
Your $correct variable should be an array like this
$correct = ['isValid'=> true]
And then you encode that
In your success jquery callback function, you can debug it to check result value
alert(data.isValid)
Upvotes: 0
Reputation: 686
Replace in your PHP
echo json_decode($incorrect);
to
echo json_enecode(array("success"=>$incorrect));
And then in javascript parse this json.
Upvotes: 0
Reputation: 57709
Your output is not true
or false
but "correct"
or "incorrect"
.
If you compare data
with those values you'll likely get better results:
if (data === "correct") {
// correct
} else {
// incorrect
}
Oh yea, and you're using json_decode
instead of json_encode
.
Upvotes: 3