Dutchdeveloper
Dutchdeveloper

Reputation: 67

PHP, Javascript Get mysql data and make calculation in javascript

I have a problem, I want to get some data from a mysql database (which isn' t a problem). Let's say i want all data from the column "Ticketkosten"

$result = $wpdb->get_results( "SELECT * FROM prijzen");
foreach ( $result as $print ) { 
   $ticketkosten = $print->Ticketkosten;
}

Then i want to get all this data and pass all the data from "Ticketkosten" to a javascript funtion, which then makes a calculation and display the final prices. The reason I want to do this is because i use a "combobox" and when i change the value in this box the calculation has to be done again real time.

The javascript code i have right now is:

var aantal_boekingen= new Array();
 aantal_boekingen["option1"]=1;
 aantal_boekingen["option2"]=2;
 aantal_boekingen["option3"]=3;
 aantal_boekingen["option4"]=4;
 aantal_boekingen["option5"]=5;

var ticketkosten = 12; //THIS SHOULD BE THE MYSQL "TICKETPRIJZEN" DATA

var boekingskosten = 1;

var transactiekosten = 0.29;


function boekingen() {
    var aantalBoekingen=0;
    var theForm = document.forms["vergelijk_form"];
     var selectedBoekingen = theForm.elements["aantal_boekingen"];

    aantalBoekingen = aantal_boekingen[selectedBoekingen.value];

    return aantalBoekingen;
}

function calculateTotal() {
    var ticketprijs = ticketkosten + ((boekingskosten + transactiekosten) / boekingen());
    var totaalPrijs = ticketprijs / boekingen();

    var x = document.getElementsByClassName("totalPrice");
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].innerHTML = "€"+totaalPrijs.toFixed(2);
    }
}

The ticketkosten which you see is now hardcoded, what i want is that this ticketkosten variable changes to the data of the database.

The javascript code is now working, but i want it to not be hardcoded.

So in short: I want to get the prices "Ticketkosten" out of the database, then pass it from php to javascript and make a calculation with these prices.

Can anyone help me out? I am stuck for more than a week now.

Upvotes: 0

Views: 766

Answers (1)

bobo_dev
bobo_dev

Reputation: 120

There are many solutions for this.

Where is your JavaScript code ? In a PHP file ? In a JS file ?

If it is in a PHP file you can do:

var ticketkosten = <?= $ticketkosten ?>;

Where $ticketkosten is the value from your database.

If you are in a JS file. You can get the value from a data-attribute like this:

var ticketkosten = document.getElementById('oneDomElement').getAttribute('data-ticketkosten');

Where oneDomElement can be whatever HTML element you want (hidden or not). It contains a data-attribute with the value from the database.

Upvotes: 1

Related Questions