0

Background: I'm building an application that is using AJAX to receive PHP arrays that have been encoded into JSON format to dynamically build tables. I have hit a snag though as although i have no compile errors I'm not seeing the array in a JavaScript popup as a test.

Error: console.log("result: "+result); in getArray in bookconf.js outputs square brackets or Array() depending on whether a variable is json_encoded or not.

Desired Effect: I would like to be able to see the php array requested output in equivalent javascript array.

The structure of the application is as follows:

  • a page receiving POSTED form variables, forming arrays and then encoding them, php/processbookconf.php
  • page including php/processbookconf.php and php/functions.php called bookconf.php

  • bookconf.php links to js/bookconf.js using script tags

  • bookconf.js makes an AJAX GET request to php/ajaxjson.php

  • ajaxjson.php includes php/processbookconf.php and php/functions, echos variables from php/processbookconf.php

  • bookconf.php calls methods from bookconf.js

code

bookconf.php

<?php
session_start();
include('php/functions.php');
include('php/processbookconf.php');
$currentuser=getUserLevel();
?>

<!doctype html>
<html lang="en-gb" dir="ltr">
<head>
</head>
<body>
<section id ="main">
<div id ="myDynamicTable">
</div>
</section>
</body>
<script src="js/functions.js"></script>
<script src="js/bookconf.js"></script>
<script>
createTable();
</script>
</html>

processbookconf.php

pasfor = array();
$passur = array();
$pasage = array();
$pasjour = array();
$pascost = array();
for ($i =0; $i<$nopass;$i++){
    $passforname = 'pasforname'.$i;
    $passfornametest = $_POST[$passforname];
    $pasfor[] = $passfornametest;


    }


$pasforJSON=json_encode($pasfor);
//echo $pasforJSON;

bookconf.js

    function getArray(seljson, callback){

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState===4){ //request done
        console.log("request =4");
        if(xmlhttp.status===200){//successfully
            console.log("status=200");
            var JSONresult = xmlhttp.responseText;
            console.log(JSONresult);
            callback(JSONresult);
            console.log("after");

        }else{console.log(xmlhttp.status);}
    }
};
xmlhttp.open("GET","/~13011450/DWBA/php/ajaxjson.php?q="+seljson,true);
xmlhttp.send(); 
}

//result is callback argument which is result



getArray('forename',function(result){
    console.log("result: " +result);
    //window.alert(result);
});

ajaxjson.php

    session_start();
include('functions.php');
$currentuser=getUserLevel();
include('processbookconf.php');
//echo $pasforJSON;

if(isset($_GET['q'])){
$q =$_REQUEST['q'];
if($q=='forename'){
    //echo'test';
        echo $pasforJSON;
}

    /*switch($q){
    case"forename":
        echo $pasforJSON;
        break;

}
*/

}
else{echo 'isnotset';}

What I've tried:

Before the current iteration i had been using using a simpler AJAX function structure. This however led to logic errors, specifically, undefined errors due to Asynchronous requests. I followed the guide laid out in the responses to this question on stackoverflow How do i return the response from an asynchronous call as well as a short tutorial on callback functions at codeburst What the heck is a callback? and have pinched code and structure from both.

Update: from testing and editing the previous iteration i did in fact find an error in the path at the top of the php/ajaxjson.php file that included the functions file. Whoops. This was found using console.log and getting 500 error. From there i got an error when i used the JSON.parse method on the xmlhttp.responseText. When i removed this i got the whole of the bookconf.php document output in the console. This, i believe was down to the fact that the php/ajaxjson.php page included the bookconf.php to get variables and that the page included HTML. I then separated the main php code into a separate file called php/processbookconf.php to receive posted variables and do the heavy lifting whilst the bookconf.php could just include it. This would allow me to include the php/bookconf.php file without returning any HTML in the AJAX response.I decided to test the PHP code again to check there was no issue. Echoing specified elements of the array, the array itself and the encoded version of the array gave the correct output, input field values from previous page. I then tested the php/ajaxjson.php page by making its code dependent on receiving a value and echoing isnotset if it doesn't. Because it didn't return that statement i then tested the query by echoing a statement if the received value equaled what had been input into the getArray function on js/bookconf.js page. I got the echoed statement returned. Inside this if statement i then tried echoing the pasforJson variable and got []. I then tried print_r on pasfor array and got Array(). To me this seems that the encoded array isn't being 'passed' properly from the processbookconf.php page. Second Update: The comment was in the php/functions page

Thank you for taking the time to read this and help.I would appreciate it if answers were in plain JavaScript, no frameworks please. Also if you could keep explanations as simple as possible as I am pretty inexperienced with web development it would be much appreciated. Kind Regards.

  • Where exactly does the error occur? Can you share an actual exception with us? – Luca Kiebel Feb 25 '19 at 19:12
  • 1
    You’ve told us a whole lotta things, except what the actual problem is. – deceze Feb 25 '19 at 19:15
  • 1
    Also, I don't think you can execute Javascript in your php the way you are trying to in bookconf.php. – Jason Pelletier Feb 25 '19 at 19:17
  • I've updated the question to include the problem. My apologies. As stated the issue is i think i should be viewing a popup showing the AJAX requested JSON object decoded but i see no popup window at all. @JasonPelletier are you referring to when i call the getArray function? – always_aim_round_corners Feb 25 '19 at 19:24
  • Yes, you can't execute js like that. You might be able to use this to eval it and then execute: http://php.net/manual/en/book.v8js.php – Jason Pelletier Feb 25 '19 at 19:32
  • Why am I not able to use the getArray function whilst i can use the createTable function? Note that the createTable() function successfully builds a 'dummy' table. Are there any other work arounds or would i have to change my code structure? – always_aim_round_corners Feb 25 '19 at 19:40
  • @always_aim_round_corners Hi why dont you use datatables with jquery and ajax promises ? I have a couple of years working with those 2 and is very easy to manage an implement if you want I can give you an example of that working with modals on bootstrap – stan chacon Feb 25 '19 at 21:24
  • Please improve the question by removing source that is not related to demonstrating the problem. e.g. if it is not related to ` case"forename"` that demonstrates the problem, it doesn't need to be there. – traktor Feb 27 '19 at 00:28
  • @stanchacon im doing this for a class at college and one of the functional requirements is vanilla JavaScript. Thanks anyway though. – always_aim_round_corners Mar 01 '19 at 17:55
  • @deceze the problem is now i dont think my php array is being properly included into the ajaxjson.php file – always_aim_round_corners Mar 01 '19 at 18:25
  • @LucaKiebel The error is not an exception but rather the array received seems to be empty. – always_aim_round_corners Mar 01 '19 at 18:26

1 Answers1

0

Including processbookconf.php in the ajaxson.php file calls the whole script again resulting in the variables that are equal to POSTED variables to have a value of "" as nothing is posted to ajaxsjon.php. This is what causes the empty array.

The solution was to set session variables in processbookconf.php and then call them with the json_encode method and echoing the result in ajaxjson.php.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92