Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Possible Duplicate:
convert php array to javascript array
passing PHP objects to javascript

Greetings Stackoverflow

I'm in quite a problem, I want to pass an array of objects from PHP to Javascript for processing. How could I do this. Tnx in advance

share|improve this question
1  
you need JSON – Alnitak May 20 '12 at 16:27
1  
json_encode the array – dInGd0nG May 20 '12 at 16:28
@Alnitak I agree with you. – Ahmed Jolani May 20 '12 at 16:28
2  
did you search Stackoverflow before asking the question? -- look at the "related" list in the side panel; this question has been asked dozens of times already. – Spudley May 20 '12 at 16:29
yes i had sir.. other posts did not say how to convert php object to javascript object – wawaragna May 20 '12 at 17:59

marked as duplicate by jprofitt, Alnitak, cbuckley, Spudley, Gordon May 20 '12 at 16:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

Often this is done using an Ajax call to your PHP app, and have PHP generate JSON with the data being sent for processing (see json_encode()).

I've also seen PHP programs generate the JavaScript with the data encoded directly in the script, but I would not recommend this approach.

share|improve this answer

When echoing the javascript in the view, you can use echo json_encode($array) to convert the PHP array to JSON which can then be inserted into a javascript variable.

share|improve this answer
... on recent versions of PHP. – Alnitak May 20 '12 at 16:28
5.2.0 - so, November 2006 – Ian Gregory May 20 '12 at 16:30
ah, if only my web host had that... :( – Alnitak May 20 '12 at 16:31
1  
@Alnitak Ah, another web host in the dark ages. There's a pure PHP version too github.com/stetsenko/code/blob/master/json_encode.php – Ian Gregory May 20 '12 at 16:32
But sir, how do I maintain the propoerties of the objects I have passed using json_encode? I have tried doing json_enode but the new array cannot access the properties of the object i just passed.. – wawaragna May 20 '12 at 17:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.