-1

Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)

I have a PHP array that I want to use in a javascript script. I suppose that I will have to convert it to a string that can be understood by javascript, and embed the string inside the script. What is the best way to accomplish this.

EDIT - This is for initial load of the page, not subsequent AJAX call

$textMessages = array();
Community
  • 1
  • 1
Mustapha George
  • 2,497
  • 9
  • 47
  • 79

3 Answers3

1

You could use JSON.

json_encode and json_decode on the server side and JSON.stringify and JSON.parse on the client side. Both client side functions are natively built-into modern browsers but if you need to support legacy browsers you could include the json2.js script to your page.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

json_encode(). Put in a PHP array, receive a string representation of a JS array.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
0

JSON is perfect for this.

echo json_encode($textMessages);

ba0708
  • 10,180
  • 13
  • 67
  • 99