1
\$\begingroup\$

I'm making a project to calculate road-tax prices based on a vehicle's weight, type and vehicle's owner's province.

For that I've received data in 9 different JavaScript files, all those files contain circa 12 arrays. I've been told I could just do this in arrays as well.

I've made this data-mapper:

var roadTaxData = {
    /**
     * provinceWeightFuelPricesVehicles has the required parameters:
     *
     * - Province
     * - Weight from
     * - benzine price
     * - diesel price
     * - LPG3/earth-gas price
     * - LPG/others price
     *
     * Data for provinceWeightFuelPricesVehicles is defined like:
     *
     * Vehicle type -> each province -> each province it's data
     */
    provinceWeightFuelPricesVehicles: {
        personen_auto: {
            noord_holland: dataNoordHolland,
            zeeland: dataZeeland
            //TODO: Add all the provinces with it's data to the personen_auto object
        },
        kampeer_auto: {
            //TODO: Add all the data, not nessecary here. You get the point.
        }
    },

    /**
     * weightFuelPricesData has the required parameters:
     *
     * - Weight from
     * - benzine price
     * - diesel price
     * - LPG3/earth-gas price
     * - LPG/others price
     *
     * Data for this is defined like:
     *
     * Vehicle type -> each province -> each province it's data
     */
    weightFuelPricesData: {
        bestel_auto_personen: {
            //TODO: Add all the provinces with it's data to the personen_auto object
        }
    },

    weightQuarterPriceYearPriceData: {
        //TODO: Add all the data, not nessecary here. You get the point.
    },
    provinceQuarterPriceYearPriceData: {
        handelaars_kenteken: {
            //TODO: Add all the data, not nessecary here. You get the point.
        },
        motoren: {
            //TODO: Add all the data, not nessecary here. You get the point.
        }
    }
};

The format of this data mapper is:

  • Vehicle format type
  • Vehicle type
  • Province
  • Province data

To parse all data to PHP, I wrote this file:

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

/**
 * Parses the road tax data (converted to JSON format) into the HTTP query
 */
function parseRoadTaxData () {
    /*
     Loop through all the road tax data
     */
    for (var vehicleFormatType in roadTaxData) {
        /*
         Define every vehicle type inside this vehicle type format
         */
        var vehicleTypes = roadTaxData[vehicleFormatType];

        /*
         Loop through the vehicle types
         */
        for (var vehicleType in vehicleTypes) {
            /*
             Add the vehicle type with it's data to the HTTP query
             */
            updateHTTPQuery(vehicleType, JSON.stringify(vehicleTypes[vehicleType]));
        }
    }
    /*
     Remove the & character from the end of the HTTP query string
     */
    trimHTTPQuery();
}

/**
 * Adds data to the HTTP query string
 *
 * @param parameterName The parameter name of the HTTP query which is getting added to the HTTP query string
 * @param value The value of the parameter name which is getting to the HTTP query string
 */
function updateHTTPQuery (parameterName, value) {
    httpQuery += (parameterName + "=" + value + "&");
}

/**
 * Removes the "&" character from the end of the HTTP query string
 */
function trimHTTPQuery () {
    httpQuery = httpQuery.replace(/&+$/, "");
}

/**
 * Gets the HTTP query string
 *
 * @returns {string} The HTTP query string
 */
function getHTTPQuery () {
    return httpQuery;
}

/*
 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(getHTTPQuery());

Which goes together with this utility file:

/**
 * 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 get with the $_POST operator
 */
function passToPHP (paramName, value) {
    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");

    /*
     Test purposes
     */
    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 + "=" + value);
}

install.php looks something like this:

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

$personen_auto = json_decode($_POST['personen_auto'], true);
$kampeer_auto  = json_decode($_POST['kampeer_auto'], true);
//... All the vehicle types


print_r($personen_auto);
print_r($kampeer_auto);
//... Testing

Questions:

  1. Is this an efficient way to make a data mapper in a JavaScript object? Isn't it better in JSON or something?
  2. Do I have to use JavaScript to parse JavaScript arrays?
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Answers

Well, I can answer your second question. You do not have to use JavaScript to parse a JavaScript array. It can be easier to do so though, as JavaScript already knows how to parse JavaScript. If you parse the JavaScript array in something else, you may have to work out the parsing rules manually.

I'm not sure that I understand your first question. What's a "data mapper" and what is it supposed to do? If all you're doing is aggregating information to send to a server, then yes, it would be better to use JSON or another transmission format. If you need to process it locally, then there's not much point in starting in JSON, as you'll have to get it into something that JavaScript can process anyway.

parseRoadTaxData

I have a bit of trouble reading this.

/*
 Loop through all the road tax data
 */
for (var vehicleFormatType in roadTaxData) {

This comment seems unnecessary. Hopefully anyone reading it will know that a for loop will loop through the contents of roadTaxData. So you can just say,

for (var vehicleFormatType in roadTaxData) {

No comment necessary.

        updateHTTPQuery(vehicleType, JSON.stringify(vehicleTypes[vehicleType]));

Given the shortness of `updateHTTPQuery, why not just say,

httpQuery += (vehicleType + "=" + JSON.stringify(vehicleTypes[vehicleType]) + "&");

It's not longer and you don't seem to be doing anything in updateHTTPQuery that makes it need abstracting. The same goes for trimHTTPQuery. It doesn't seem to do enough to justify its own function.

passToPHP(getHTTPQuery());

Again, why bother with a getter for a global variable? More importantly though, it doesn't match the function definition:

function passToPHP (paramName, value) {

This expects a name/value pair, but you are passing it a query string. I don't see how this could work.

Alternative

You could make this whole thing simpler:

function passToPHP () {
    var httpc = new XMLHttpRequest(); // simplified for clarity"
    httpc.open("POST", INSTALL_FILE, true); // sending as POST

    httpc.setRequestHeader("Content-Type", "application/json; charset=UTF-8");

    /*
     Test purposes
     */
    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({ roadTaxData:JSON.Stringify(roadTaxData) });
}

You can see an example here.

You don't need the parseRoadTaxData function at all. Just pass the whole thing to PHP and work with it there.

PHP Usage

Example usage in PHP. Replace

$personen_auto = json_decode($_POST['personen_auto'], true);
$kampeer_auto  = json_decode($_POST['kampeer_auto'], true);

with

$roadTaxData = json_decode($_POST['roadTaxData'], true);
$personen_auto = $roadTaxData['provinceWeightFuelPricesVehicles']['personen_auto'];
$kampeer_auto  = $roadTaxData['provinceWeightFuelPricesVehicles']['kampeer_auto'];
\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.