I'm trying to pass a PHP variable to Javascript like this..
var url = <?php echo $urlArray[0]; ?>;
The contents of $urlArray[0] is a string from a json decoded array
"baby"
When I run the code I get the error..
Uncaught ReferenceError: baby is not defined
pilsetnieks
10.5k12 gold badges51 silver badges61 bronze badges
asked Jun 12, 2013 at 23:44
David Folksman
2353 gold badges9 silver badges25 bronze badges
2 Answers 2
var url = "<?php echo $urlArray[0]; ?>";
you forgot the quotes.
If you need to export more complicated data structure, you may need json_encode. This might be helpful if exporting arrays and/or objects.
answered Jun 12, 2013 at 23:46
Saturnix
10.6k19 gold badges70 silver badges129 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Saturnix
you don't even know how many times I've forgot to use
" in the dialogue between PHP and JS. I think switching to json encode will remove the need of quotes. Also that can lead to HUGE improvement: f.e. you can export arrays and arrays of object. You can set a defined data structure (agreed in both php and js), send it back and forth between the two and have your structure instantly recognized. If you're into js/php dialogue, you should really try to export some array of objects into js to see what I'm talking about.David Folksman
Thanks I marked the answer correct. I'll have a play about and see what you mean! :)
Sam Dufel
PHP won't put it there for you - that is incorrect. If you're json_encoding a string, it will be automatically quoted.json_encode is your friend - use to wrap anything you're trying to pass to javascript.
http://php.net/manual/en/function.json-encode.php
var url = <?php echo json_encode($urlArray[0]); ?>;
answered Jun 12, 2013 at 23:46
Sam Dufel
17.6k3 gold badges51 silver badges52 bronze badges
2 Comments
David Folksman
Sorry, i'm a bit new to this.. why would I want to re-encode it, after I just decoded it?
Sam Dufel
Variables echoed into javascript need to be properly escaped. There are a number of things in strings which can wreak havoc with your javascript if they are echoed directly.
json_encode() will return a value which can be safely output to your javascript.default