0

I need to send php string to javascript. I use json_decode.

var mystring = '<?php echo json_encode($phpstring)?>';

What would be a proper way to output this string in javascript?

jQuery.parseJSON(mystring)

shows error Uncaught SyntaxError: Unexpected token. I don't understand why. Isn't json_encode supposed to put a string into a proper json obj?

JohnyFree
  • 1,319
  • 3
  • 22
  • 35
  • What is the value of $phpstring? Is it a valid Json ? – Pascal Le Merrer Mar 11 '14 at 18:28
  • It is a dynamic string from user. I thought it is safe to use json_encode. Based on [this answer](http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines) json_encode could be used to convert php string into javascript. – JohnyFree Mar 11 '14 at 18:40
  • So it can only work if the user enters a valid Json string. Your message suggest it's not the case. You should enclose your call to parseJSON in a try catch / clause (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) and display an error message if an error is catched, that is to say if the string is not a valid JSON string. – Pascal Le Merrer Mar 11 '14 at 20:05
  • Thank you. I realized that json_encode won't be ok in my case. I will use `var myvar = decodeURIComponent("");`. – JohnyFree Mar 11 '14 at 20:17

0 Answers0