-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,467
  • 9
  • 46
  • 76

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
  • 994,864
  • 265
  • 3,241
  • 2,902
1

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

Matti Virkkunen
  • 61,328
  • 9
  • 119
  • 152
0

JSON is perfect for this.

echo json_encode($textMessages);

ba0708
  • 9,544
  • 12
  • 64
  • 99