CodeIgniter Forums

Full Version: Passing array to Javascript code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]taizen[/eluser]
(Pardon my rookieness)

I've created a view from this Flot (jQuery plugin) example: http://people.iola.dk/olau/flot/examples/real-data.html

Then i want to pass an array with data collected from a database to the Javascript code, so that the graph is updated according to the database content.

I guess this is really simple but my knowledge of PHP, CI and JS is rather limited, so a little guidance here is greatly appreciated.

El Forum

[eluser]libnac[/eluser]
Does Flot use JSON in order to represent graphics?

i am viewing the code you put on your question ...

"usa": {
label: "USA",
data: [[1988, 483994], [1989, 479060], [1990, 457648], [1991, 401949], [1992, 424705], [1993, 402375], [1994, 377867], [1995, 357382], [1996, 337946], [1997, 336185], [1998, 328611], [1999, 329421], [2000, 342172], [2001, 344932], [2002, 387303], [2003, 440813], [2004, 480451], [2005, 504638], [2006, 528692]]
},

I think this is json.. then you must to echo your results inside the javascript function that creates this graphics.

El Forum

[eluser]taizen[/eluser]
[quote author="libnac" date="1214164781"]Does Flot use JSON in order to represent graphics?
[/quote]

I have no idea, i must admit...

[quote author="libnac" date="1214164781"]
I think this is json.. then you must to echo your results inside the javascript function that creates this graphics.[/quote]

That's brilliant! Works fine. I just put
Code:
<?php echo $results[0]; ?>
in my view.

Maybe by passing the entire dataset as a string and the echo it would be the best?

Thanks!

El Forum

[eluser]libnac[/eluser]
Yes, I think so... but what's in $results[0]? in order to generate a good json you must follow some rules

El Forum

[eluser]Matthieu Fauveau[/eluser]
If you have PHP5 you can use json_encode() function to generate a proper JSON string.

El Forum

[eluser]taizen[/eluser]
json_encode() was the best way of doing it. Really!

El Forum

[eluser]Matthieu Fauveau[/eluser]
Glad to be of help Wink