I'm bit stuck, i have two functions that call a fill and return the result with JSON.parse. But when i console.log the result i get "undefined".
This is my function that handles the requests:
function caller(url,cfunc){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function call_data(url,data){
caller(url,function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
return( JSON.parse (xmlhttp.responseText) );
}
});
}
The call is here:
result = call_data('./chk_login.php',0);
console.log(result);
According to Chrome im getting the xhr request perfectly fine and shows the output. But console.log shows undefined... so you know this is my PHP script too:
<?
$var = 1;
echo json_encode($var);
exit;
?>
What could be causing the problem ???
Hope you can help! Thanks!
Since this is asynchronous (that's what the A in AJAX stands for, after all), you can't simply return
a value and expect it to come back magically. Instead, manipulate the data within a callback (you're 80% of the way there already).
function call_data(url,data){
caller(url,function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log( JSON.parse (xmlhttp.responseText) );
ajaxResult = JSON.parse (xmlhttp.responseText);
}
});
}
var ajaxResult;
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.