0

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

2 Answers 2

3
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.

3
  • 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. Commented Jun 13, 2013 at 0:00
  • Thanks I marked the answer correct. I'll have a play about and see what you mean! :) Commented Jun 13, 2013 at 0:02
  • PHP won't put it there for you - that is incorrect. If you're json_encoding a string, it will be automatically quoted. Commented Jun 13, 2013 at 0:51
2

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]); ?>;
2
  • Sorry, i'm a bit new to this.. why would I want to re-encode it, after I just decoded it? Commented Jun 12, 2013 at 23:51
  • 1
    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. Commented Jun 13, 2013 at 0:48

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.