I'm struggling to find out why my AJAX function is returning undefined
, I can output the function output to a div in the html successfully by adding document.getElementById("aDisplayDiv").innerHTML = characterStatsArray[a]
into the function but I don't wish to do this, I want the function to just output the relevant array figure so I can drive calculations from it.
When i just output getCharStats(2)
(or any other parameter) the result is displayed on the page as undefined
.
JS
function getCharStats(a) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var characterStatsArray = JSON.parse(this.responseText);
return characterStatsArray[a];
}
};
xmlhttp.open("GET", "loadCharacterStats.php", true);
xmlhttp.send();
}
var userHP = getCharStats(3);
document.getElementById("mobhealthbar").innerHTML= "MOB HP: " + mobHP;
PHP
<?php
session_start();
require("db.php");
require("DatabaseObject.php");
$database = new DatabaseObject($host, $username, $password, $database);
$getCharacter = $_SESSION["ActiveCharacter"];
$sessionid = $_SESSION['user_id'];
$sql = $database->query("SELECT `character_name`,`userid`,`character_class`,`level`,`health`,`max_health`,`mana`,`strength`,`constitution`,`wit`,`intelligence` FROM `character` WHERE `userid` = '$sessionid' and `character_name` = '$getCharacter'") or die("Error: ". mysql_error(). " with query ");
while ($row = $sql->fetch_assoc()){
//creates a JSON string to export the character sta
$characterStatsArray = array($row['character_name'],$row['character_class'],$row['level'], $row['level'],$row['health'],$row['mana'],$row['strength'],$row['constitution'],$row['wit'],$row['intelligence']);
$charStatsJSON = json_encode($characterStatsArray);
echo $charStatsJSON;
}
?>
UPDATE
So I've taken the advice that i need to use a callback, after readying through the suggested and thread and some further reading i'm still returning "undefined", is my callback logic wrong :|?
The callback I've added looks as follows;
UPDATED JS
function getCharStats(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
callback
}
};
xmlhttp.open("GET", "loadCharacterStats.php", true);
xmlhttp.send();
}
function myCallback(result) {
var characterStatsArray = JSON.parse(this.responseText)
return characterStatsArray[result];
};
getCharStats(myCallback);