0

I experience the problem with parsing json encoded object in js. JSON.parse(word_array); with error Uncaught SyntaxError: Unexpected identifier

My investigation showed that object word_array does not exist because of wrong-formation in PHP: it has a unescaped single quote' inside, thus making js consider it as the end of the string.

I form encoding next way:

echo "<script>var word_array = '";
echo  json_encode($word_set);
echo "';\n";

As far as I know, json_encode should escape all undesirable charactets like ' but it does not. What might be the problem?

My php version: Version PHP: 5.3.13 And $word_set is array of assoc. array:

$word_set = array();
while($stmt->fetch())
{
  $word_set_tmp[] = array(
    'word' => $word, 
    'definition' => $def
  );
  array_push ($word_set,$word_set_tmp);
} 
6
  • 2
    Please show the output of json_encode, showing the claimed unescaped quote Commented Jul 29, 2014 at 14:26
  • 1
    Why would you assign string and then parse it when you could assign json right away (without wrapping it in quotes). Commented Jul 29, 2014 at 14:27
  • I cut the end (as it is big). var word_array = '[{"word":"Abeyance","definition":"a temporary suspension of activity."},{"word":"Akimbo","definition":"having one's hands in a bent position on the hips."} Commented Jul 29, 2014 at 14:27
  • The problem in one's Commented Jul 29, 2014 at 14:28
  • @Cthulhu funny thing: your suggestion fixes his issue too, as afaik ' shouldnt be escaped Commented Jul 29, 2014 at 14:30

1 Answer 1

5

The problem is you surrounding an array declaration in single quotes, remove them and all is well:

echo "<script>var word_array = " . json_encode($word_set) . ";";

As a side note, i find when i must mix php with anything else (html, js) then its best to exit php mode and write html/js, echoing out the required php vars, rather than echo out html/js:

<?php 
    $word_set = $db->somfunc();
?>
<script>
    var word_array="<?php echo json_encode($word_set);?>";
    alert(word_array[1].definition);
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.