Really simple javascript function that does an AJAX call. When the function returns, it returns with a boolean value (not a string). Right now, for testing purposes, I have it set to always return 'true'. Problem is that I don't seem to be able to capture this value so that I can evaluate it. Here is the code:
function verifySession() {
var xmlhttp = new XMLHttpRequest();
var returnValue = xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// this is wrong, but I don't know how to alter it for boolean values
session_verified = xmlhttp.responseText;
// this outputs as empty, even though the return value is true
console.log(session_verified);
if (!session_verified) {
console.log("false value returned");
return false;
} else {
console.log("true value returned");
return true;
}
}
}
xmlhttp.open("GET", "/scripts/session_verifier.php", false);
xmlhttp.send();
return returnValue;
}
session_verifier.php basically looks like this (again, grossly simplified for testing purposes):
<?php
return true;
?>
I've used this many times for functions that return strings, but this time I need it to return a boolean value. How can I capture its return value? Thanks!
In your php script. Try returning the string value true ("true"), or the number 1
then in your JS
session_verified = Boolean(xmlhttp.responseText);
Testing your code I've noticed that the result is empty, as you can see here:
readyState: 4
response: ""
responseText: ""
responseType: ""
responseXML: null
But if you change a bit your PHP, you can see the result:
header('Content-Type: application/json');
echo json_encode(array(
'success' => true,
));
I hope it helps you.
Cheers,
Since the XMLHttpRequest response might be a text or XML, you can handle the Boolean return value this way.
// PHP
function your_function(){
if($something == TRUE){
return 1;
}else{
return 0;
}
}
// JavaScript
xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if(parseInt(xhr.responseText)){
// true
}else{
// false
}
}
};
xhr.send();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.