CodeIgniter Forums
Passing array to Javascript code - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Passing array to Javascript code (/showthread.php?tid=9339)



Passing array to Javascript code - El Forum - 06-22-2008

[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.


Passing array to Javascript code - El Forum - 06-22-2008

[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.


Passing array to Javascript code - El Forum - 06-22-2008

[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!


Passing array to Javascript code - El Forum - 06-22-2008

[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


Passing array to Javascript code - El Forum - 06-22-2008

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


Passing array to Javascript code - El Forum - 06-22-2008

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


Passing array to Javascript code - El Forum - 06-22-2008

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