0

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);
Joe Young
  • 3
  • 2
  • The calling function needs to wait until the ajax request completes. so you should either callback or use promises. – Padmanabha Jul 16 '18 at 14:29
  • Thanks for the response i've updated the post with updated javascript, i'm still getting the same issue, i presume i'm missunderstanding callbacks? – Joe Young Jul 16 '18 at 16:52
  • yes you should do callback(characterStatsArray[a]) from the getCharStaus function. which is populated to result in calling function – Padmanabha Jul 16 '18 at 17:17
  • function getCharStats(a,callback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var characterStatsArray = JSON.parse(this.responseText) callback(characterStatsArray[a]) } }; xmlhttp.open("GET", "loadCharacterStats.php", true); xmlhttp.send(); } function myCallback(result) { alert(result); }; getCharStats(3,myCallback); – Padmanabha Jul 16 '18 at 17:23
  • Thanks for your help here, it still returns undefined, however the alert does provide a result from JSON which is good news, there is an error in the console though, "Uncaught TypeError: callback is not a function" . any ideas? – Joe Young Jul 16 '18 at 18:02
  • I got rid of the error by adding a check for callback "if(callback) callback(characterStatsArray[a])" I still cannot get the damn thing to return a result, I'm only able to output the result by using .innerHTML and writing to a div or using an alert, return or .value only outputs undefined >:|. – Joe Young Jul 16 '18 at 23:34

0 Answers0