Passing Php variables to a .js file

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
md7dani
Forum Newbie
Posts: 13
Joined: Fri Oct 23, 2009 1:55 am

Passing Php variables to a .js file

Post by md7dani »

I have a php file with data from Mysql db. I need to pass the data to a .js file. I've looked at it and can't find a solution for it. I've looked at the following solutions:

* pass the variables with jQuery
* pass the data in a textfile and read it from the .js file

What is the best way to solve this problem?

I'm running on a local apache server, with Php and Mysql. Thnx!
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Passing Php variables to a .js file

Post by josh »

Usually the best practice is to issue an ajax call for the data (so yes, the .txt file). It depends on the size of the data, I'd say. You could have PHP create a JSON string (Zend_Json), and then output that in a <script> tag as a global javascript variable, and then read that value back with javascript - although thats more convenient for small data, I'd say its bad practice, but should be done for optimization (just not prematurely).
Post Reply