I have to create a javascript array whose elements are fetched by php from a database. Is it possible? If so, how?
(I dont want to use ajax to do that)
I have to create a javascript array whose elements are fetched by php from a database. Is it possible? If so, how? (I dont want to use ajax to do that) |
|||||
|
Collect the values in an array and convert it to JSON with
|
|||
|
Answer 1: yes, it can be done. Answer 2: Here's how:
Cheers! |
|||||||||||||||||
|
|
|||
|
If you can loop through the database contents, creating an array is simple:
Loop through array here and add commas to separate values.
Your myArray variable will be available client-side. It should look something like:
Alternatively and to avoid an extra comma due to loop-based string concatenation, you can write the variable to the client as follows:
...and do the following for each data row:
This is effective, though not quite as clean as the previous approach. You will end up with code similar to the following:
My apologies for not being too familiar with PHP, but this is something that can be done with any server-side language. |
|||||
|
Here is a solution that correctly deals with single quotes in the data: First retrieve the database data, for example with mysqli_ functions:
Then convert it to JSON, escape single quotes and output the JavaScript:
Note that |
|||
|