Skip to content
Advertisement

Using a php array as argument to a JavaScript function

I’ve a function which feeds a chart with fixed data:

JavaScript

I’d like to replace the fixed data with the one read from a DB table containing two columns: date and temperature. The read data is stored in the $json variable:

JavaScript

Here’s my bad code:

JavaScript

How can I make this work?

EDIT: Code after being edited with @trincot’s suggestions:

JavaScript

Original code is here:chart code

Advertisement

Answer

Given that your $json is an array of objects with two properties, you’ll need to convert that to an array of arrays (pairs):

JavaScript

So this just injects the whole JSON inside the array literal that is given as argument to arrayToDataTable. The .map call converts the plain objects to pairs and:

  • the date strings are converted to Date objects
  • the temperature strings are converted to numbers. It is a pity that your PHP code has somehow stored the temperatures as strings. That is odd. It would be better practice to have them there with a number data type, not a string data type.

When you look at the source via your browser, you should see something like this:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement