Reputation: 31893
My projects are becoming more and more JS heavy. The issue is that most of my data is on the server side (PHP). What are some clean ways for transporting this data over to the client side (code samples for extra brownie points)?
Some ways I am considering - which of these are best?:
1) Use php to "echo" directly to js variables. 2) Use php to write to HTML elements and then use js to retrieve from the dom. 3) Use ajaxcall
Thoughts?
Upvotes: 2
Views: 634
Reputation: 29160
The way I have found to perform the best is as follows.
I make AJAX calls to a PHP page which performs some action, and returns data. Once that PHP has all the data it needs to return, I echo the data (as an array) in JSON format.
fetchUserInfo.php
die (
json_encode(
array(
"username" => "Dutchie",
"id" => "27"
)
)
);
Then, you can use javascript (although I suggest jQuery for AJAX browser compatibility) to fetch the data into a json object.
JS
$.getJSON(
'fetchUserInfo.php?',
function(jsonObject) {
alert(jsonObject.username);
}
);
Upvotes: 1
Reputation: 145482
All of those methods are workable. As said, it really depends on the use case.
1) Use php to "echo" directly to js variables.
Which is a necessity if you need some data at "initialization time". If your initial page display depends on some state variable, there's no way around this method.
2) Use php to write to HTML elements and then use js to retrieve from the dom.
I consider this the lazy option. It allows to update data without coding two different ways to retrieve it. Since jQuery provides .load("file.php div.data")
you often can reuse existing output templates.
3) Use ajax calls
That's probably the best option for querying. Especially if you need information from the database or poll some status this is the preferred way. Use JSON for returning data, but prefer GET/POST variables for client->server communication.
Upvotes: 4
Reputation: 919
i personnally use a native PHP array and use json_encode and json_decode over it to get a clean Javascript-parsable array. You can have a look at the manual here: http://php.net/manual/en/function.json-encode.php
Upvotes: 1
Reputation: 11779
4) Use JSON http://www.php.net/manual/en/function.json-encode.php - returned value is an associated array for JavaScript
Upvotes: 1
Reputation: 17169
I prefer JSON with json_encode();
in php using ajax call to retrive it.
Upvotes: 2