Consider the following:
<?php
//daytime_check.php
$is_daytime = false;
if ($is_daytime) {
echo '1';
} else {
echo '0';
}
?>
==================================================================================
// javascript/jQuery
$.ajax({
type: 'POST',
url: 'daytime_check.php',
success: function(response) {
if(response == false) {
alert('Goodnight, brother');
} else {
alert('Day\'s a wastin, brother');
}
},
error: function() {
//handle error
}
});
This is how I have heretofore handled the responses from my AJAX’d PHP scripts. I’m hoping someone out there can give me some hints on a better way, as this current method feels pretty clunky.
Especially clunky is handling the “filtering” of the PHP script’s output on the JS side. For example:
In this case, the response from PHP is going to be a JS var response ='0'. Now one can’t simply use if (!response)... in JS to filter, because apparently !response evaluates to false, while, interestingly, response == false evaluates to true. Something to do with type juggling, I suppose.
Since the only way I can return things from PHP is in text (echo statements), I can’t return proper true/false values to filter on when I get to the JS side. Is there a better way to handle this?
I hope this made at least a little sense.
You can stil return any type you would like to. Just use JSON response.
This will output this string:
And on client side jQuery will parse this response: