Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JS array with JS and then passing it to PHP

I'm making a system for calculating road taxes in the netherlands, there for i got a few JS arrays (where the data is in) which i'm parsing with JS (all at the same time, because it's the same format of data), then passing it to PHP as JSON format using the XMLHttpRequest object.

For this i first made this data mapper:

var roadTaxData = {
    provinceWeightFuelPricesData: {
        personen_auto: {
            noord_holland: dataNoordHolland,
            zeeland: dataZeeland
            //TODO: Add all the provinces with it's data to the personen_auto object
        },
        kampeer_auto: {
            noord_holland: dataNoordHolland2,
            zeeland: dataZeeland2
        }
    }
}

The format of this is:

  • Vehicle type
  • Which province
  • The data belonged to that province.

I've then made this small parser to parse it to an array:

/*
 Loop through all the specific vehicle types inside the provinceWeightFuelPricesData object
 */
for (var vehicleType in roadTaxData.provinceWeightFuelPricesData) {
    /*
        Where the data is getting stored for each vehicle type
     */
    var data = {},
        /*
            Every province with its data contained in the vehicle type
         */
        provinces = roadTaxData.provinceWeightFuelPricesData[vehicleType];

    /*
     Loop through all province's with its data in the specific vehicle type
     */
    for (var province in provinces) {
        /*
         Define each province data
         */
        var provinceData = provinces[province];
        /*
         Add the province to the object as an key
         */
        data[province] = [];
        /*
         Loop through the data which belongs to every province
         */
        for (var provinceDataIndex = 0; provinceDataIndex < provinceData.length; provinceDataIndex++) {

            /*
             Add the province data to the array
             */
            data[province].push(provinceData[provinceDataIndex]);
        }
        console.log('Parsed a the province: ' + province + " from the vehicle type " + vehicleType);
        console.log('');
    }
    console.log('Parsed the vehicle type: ' + vehicleType);
    console.log('');
    console.log(data);
    passToPHP(vehicleType, JSON.stringify(data));
}

This is all going great, and gives me back the correct array with data when i do this:

console.log(data);

But when i've passed it to PHP with this method:

function passToPHP (paramName, data) {
    if (typeof paramName === "string" && typeof data === "string") {
        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");

        /*
         For testing
         */
        httpc.onreadystatechange = function () { //Call a function when the state changes.
            if (httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
                console.log(httpc.responseText); // some processing here, or whatever you want to do with the response
            }
        };
        httpc.send(paramName + "=" + data);
    }
}

With this PHP file:

header('Content-Type: application/json');

$personen_auto = $_POST['personen_auto'];
$kampeer_auto  = $_POST['kampeer_auto'];


print_r(json_decode($personen_auto));
print_r(json_decode($kampeer_auto));

I get this error first, which doesn't reconize the kampeer_auto index from $_POST, which i actually send:


Notice: Undefined index: kampeer_auto in C:\Users\Bas\Documents..\Cars\install.php on line 6

Then the data log of the personen_auto object.

Then another error with this message, which does't reconize the personen_auto index, which i also just parsed and printed out?


Notice: Undefined index: personen_auto in C:\Users\Bas\Documents..\Cars\install.php on line 5

Questions

  • How does this come that it doesn't reconize those $_POST variables?
  • How will i be able to make PHP receive more then only 1 $_POST index at the time?

My own try

I've tried putting the passPHP() method outside of the for loop, like this:

/*
 Loop through all the specific vehicle types inside the provinceWeightFuelPricesData object
 */
for (var vehicleType in roadTaxData.provinceWeightFuelPricesData) {
    /*
        Where the data is getting stored for each vehicle type
     */
    var data = {},
        /*
            Every province with its data contained in the vehicle type
         */
        provinces = roadTaxData.provinceWeightFuelPricesData[vehicleType];

    /*
     Loop through all province's with its data in the specific vehicle type
     */
    for (var province in provinces) {
        /*
         Define each province data
         */
        var provinceData = provinces[province];
        /*
         Add the province to the object as an key
         */
        data[province] = [];
        /*
         Loop through the data which belongs to every province
         */
        for (var provinceDataIndex = 0; provinceDataIndex < provinceData.length; provinceDataIndex++) {

            /*
             Add the province data to the array
             */
            data[province].push(provinceData[provinceDataIndex]);
        }
        console.log('Parsed the province: ' + province + " from the vehicle type " + vehicleType);
        console.log('');
    }
    console.log('Parsed the vehicle type: ' + vehicleType);
    console.log('');
    //console.log(data);
}
passToPHP(vehicleType, JSON.stringify(data));

But that passed only one variable to PHP (which was kampeer_auto).

like image 513
Bas Avatar asked Dec 21 '14 20:12

Bas


2 Answers

the code is sending only one vehicleType per call to php. The relevant code is

for (var vehicleType in roadTaxData.provinceWeightFuelPricesData) {
    data = ...
    passToPHP(vehicleType, JSON.stringify(data));
}

The first call passes 'personen_auto' only (and kampeer_auto is undefined); the second call passes only 'kampeer_auto' and personen_auto is undefined.

The revised version of the code that moves passToPHP outside the loop still resets data each time through the loop, so at the bottom data will contain only the very last auto's provinces.

To pass all autos, data needs to be appended to (not re-initialized), data has to be gathered into auto-specific sections (not intermingled), and passToPHP needs to build a multi-parameter query string, one per auto. All that will pretty much rebuild the roadTaxData object.

Or just pass all of roadTaxData.provinceWeightFuelPricesData to php and have php loop and separate the auto types.


Edit: you don't need to convert objects to arrays when passing them to php. Php's json_decode() can decode objects into associative arrays when the optional second parameter is set to true, as json_decode($data, true). Simply

passToPHP('json', JSON.stringify(roadTaxData.provinceWeightFuelPricesData));

and in php

$data = json_decode($_POST['json'], true);
$kampeer_auto = $data['kampeer_auto']);
$personen_auto = $data['personen_auto']);
like image 73
Andras Avatar answered Oct 30 '22 10:10

Andras


Try putting declaration for data outside the loop. It's currently getting reset/cleared for each entry in roadTaxData.provinceWeightFuelPricesData so you will only ever send the last entry to the server.

var data = {};

for (var vehicleType in roadTaxData.provinceWeightFuelPricesData) {

Then, as @Andras suggested, you need to decode the JSON on the server side:

$data = json_decode( $_POST['json'], true );

$personen_auto = $data['personen_auto'];
$kampeer_auto  = $data['kampeer_auto'];
like image 32
Phil Avatar answered Oct 30 '22 09:10

Phil