简体   繁体   中英

PHP won't load data on first page load at JavaScript HTTP request

I'm sending data with a JavaScript HTTP request to PHP, I want the PHP to keep it in it's memory. Therefor, i'm using $_SESSIONS 's. I'm doing this because i dont want to do any calculation or HTML deployment with JavaScript.

Here's my method how i'm sending data to PHP:

/**
 * The PHP file which receives the data
 *
 * @type {string} The php filename
 */
const INSTALL_FILE = "install.php";

/**
 * Passes roadTaxData to the php install file which could be getData with the $_POST operator
 */
function passToPHP (paramName, data) {
    var httpc = new XMLHttpRequest(); // simplified for clarity"
    httpc.open("POST", INSTALL_FILE, true); // sending as POST
    httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    httpc.send(paramName + "=" + data);
}

I'm using the method like this:

/**
 * @type {string} The data which is getting send to PHP
 */
var data = "";

/**
 * Parses the road tax data and stores it into the data string as JSON format
 */
function parseRoadTaxData () {
    var object = {};
    /*
     Loop through all the road tax data
     */
    for (var vehicleFormatType in roadTaxData) {
        /*
         Define all vehicle types which belong to that vehicle type format
         */
        var vehicleTypes = roadTaxData[vehicleFormatType];

        /*
         Loop through all the vehicle types
         */
        for (var vehicleType in vehicleTypes) {
            /*
             Add the vehicle data to the JSON object
             */
            object[vehicleType.toLowerCase()] = vehicleTypes[vehicleType];
        }
    }
    /*
     Parse the javascript object (converted to JSON format) into the data string.
     */
    data = JSON.stringify(object);
}

/**
 * Gets the data which is going to be send to PHP
 *
 * @returns {string} The JSON data string
 */
function getData () {
    return data;
}

/*
 Call the function to parse all data into the HTTP query string
 */
parseRoadTaxData();

/*
 Call the function to pass the whole HTTP query to PHP in seperate $_POST variables
 */
passToPHP('road-tax_data', getData());

The install.php file, which is receiving the data looks like this: It opens a session and stores the data in the RoadTaxDataTemporaryRegistry class.

require "RoadTaxDataTemporaryRegistry.php";

/*
 * Start the session
 */
session_start();


RoadTaxDataTemporaryRegistry::store(json_decode($_POST['road-tax_data'], true));

My RoadTaxDataTemporaryRegistry class looks like this:

/**
 * Storage for all road tax data
 */
class RoadTaxDataTemporaryRegistry
{
    /**
     * The character which gets and sets the specific $_SESSION
     */
    const SESSION_NAME = 'rtd';

    /**
     * Stores all data in a session
     *
     * @param $data array The data which is getting stored
     */
    public static function store ($data) {
        $_SESSION[self::SESSION_NAME] = $data;
    }

    /**
     * Gets the road tax data of a vehicle
     *
     * @param string $vehicle
     *
     * @return array
     */
    public static function getStorageByVehicle ($vehicle) {
        return $_SESSION[self::SESSION_NAME]["$vehicle"];
    }
}

This class does nothing more then just storing variables into a specific $_SESSION key.

My index.php looks like this:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="data/js-files/data_personen_auto.js" type="application/javascript"></script>
    <script src="js/road_tax_data_mapper.js" type="application/javascript"></script>
    <script src="js/utility.js" type="application/javascript"></script>
    <script src="js/data_parser.js" type="application/javascript"></script>
</head>
<body>

<?php  
    require "RoadTaxDataTemporaryRegistry.php";

    session_start();

    var_dump(RoadTaxDataTemporaryRegistry::getStorageByVehicle($myCar));

?>
</body>
</html>

I first import all the JavaScript scripts, which are sending the data to PHP.

Then in the body of my html page, i'm opening the session and calling up and printing out the data i've just parsed in that class via the HTTP request.

Problem

When I open this for the first time in my browser (open via my IDE PhpStorm) i get this error message:

Notice: Undefined index: rtd in C:\\Users\\Bas.\\Cars\\RoadTaxDataTemporaryRegistry.php on line 30 NULL

When I refresh the page, the data is getting printed out how it should:

array(1) { ["noord_holland"]=> array(46) { [0]=> string(14) "1#26#90#26#101" [1]=> string(17) "551#34#109#34#124" [2]=> string(17) "651#42#129#42#147" [3]=> string(17) "751#55#154#55#175" [4]=> string(17) "851#73#189#87#203" [5]=> string(18) "951#94#223#123#238" [6]=> string(20) "1051#115#257#159#273" [7]=> string(20) "1151#137#290#195#309" [8]=> string(20) "1251#158#324#230#344" [9]=> string(20) "1351#180#358#266#379" [10]=> string(20) "1451#201#392#302#414" [11]=> string(20) "1551#222#426#338#449" [12]=> string(20) "1651#244#460#374#485" [13]=> string(20) "1751#265#494#409#520" [14]=> string(20) "1851#286#528#445#555" [15]=> string(20) "1951#308#562#481#590" [16]=> string(20) "2051#329#596#517#625" [17]=> string(20) "2151#351#630#553#661" [18]=> string(20) "2251#372#664#588#696" [19]=> string(20) "2351#393#698#624#731" [20]=> string(20) "2451#415#732#660#766" [21]=> string(20) "2551#436#766#696#801" [22]=> string(20) "2651#458#800#732#837" [23]=> string(20) "2751#479#834#768#872" [24]=> string(20) "2851#500#868#803#907" [25]=> string(20) "2951#522#902#839#942" [26]=> string(20) "3051#543#936#875#977" [27]=> string(21) "3151#564#969#911#1013" [28]=> string(22) "3251#582#1000#943#1044" [29]=> string(22) "3351#600#1030#975#1075" [30]=> string(23) "3451#617#1060#1006#1106" [31]=> string(23) "3551#634#1089#1038#1138" [32]=> string(23) "3651#651#1119#1070#1169" [33]=> string(23) "3751#669#1149#1102#1200" [34]=> string(23) "3851#686#1179#1133#1231" [35]=> string(23) "3951#703#1209#1165#1262" [36]=> string(23) "4051#720#1239#1197#1293" [37]=> string(23) "4151#738#1269#1228#1324" [38]=> string(23) "4251#755#1298#1260#1355" [39]=> string(23) "4351#772#1328#1292#1386" [40]=> string(23) "4451#790#1358#1324#1418" [41]=> string(23) "4551#807#1388#1355#1449" [42]=> string(23) "4651#824#1418#1387#1480" [43]=> string(23) "4751#841#1448#1419#1511" [44]=> string(23) "4851#859#1477#1450#1542" [45]=> string(23) "4951#876#1507#1482#1573" } } 

Question

How do I make the page automaticly load the data without having to refresh the page?

My own try

I've put this JavaScript code into my passPHP() function:

httpc.onreadystatechange = function () { //Call a function when the state changes.
    if (httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
        window.location.href = "index.php";
    }
};

This automaticly refreshed the page, but this was to slow and you actually saw the page that said that the array index was'nt defined.

  • Note: I dont want to use jQuery

I should use AJAX again to load the values once the former request returns.

The flow:

  1. Use AJAX to post your data into a session using parseRoadTaxData
  2. Attach an event handler to that AJAX call onreadystatechange
  3. Wait for a readystate of 4 and make a new AJAX call now retrieving your session data through a PHP file running RoadTaxDataTemporaryRegistry::getStorageByVehicle($myCar)

extending your AJAX call with onreadystate

function setAndLoadData(INSTALL_FILE, paramName , data)
{
    var httpc = new XMLHttpRequest(); // simplified for clarity"
    httpc.open("POST", INSTALL_FILE, true); // sending as POST
    httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    httpc.onreadystatechange = retrieveVarsFromPHP //<-- call this on readystatechange.
    httpc.send(paramName + "=" + data);
}

function retrieveVarsFromPHP()
{
    if (this.readyState == 4)
    {
         //AJAX call to retrieve data.
         var httpc = new XMLHttpRequest(); // simplified for clarity"
         httpc.open("get", retrieveSessionData.php, true);
         httpc.onreadystatechange = function()
         {
             if (this.readyState == 4)
             {
                 sessionData = JSON.parse(this.responseText); //Store the data in a global, which can be accessed in the index.html
                 callBack() //this can be a function in your page called upon to handle displaying the retrieved data.
             }
         } 
         httpc.send();
    }

} 

PHP file retrieveSessionData.php

<?php
require "RoadTaxDataTemporaryRegistry.php";

session_start();

echo (RoadTaxDataTemporaryRegistry::getStorageByVehicle($myCar));
?>

Execute on index.php

 <script>
      setAndLoadData();
 </script>

Your problem with retrieving the data lays in the asynchronous part of AJAX . The data isn't really set yet while PHP starts parsing the data. You need to wait for this to finish. The refreshing of the page was a hint in that direction, but you still can't rely on that. Because the fact that the page finishes loading says nothing about the fact that of your asynchronous AJAX call running besides the page-loading is finished.

I hope I made sense.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM