0

I have this array ($test) in PHP

array (size=4)
  1 => string '[email protected]' (length=17)
  2 => string '[email protected]' (length=17)
  3 => string '[email protected]' (length=17)
  4 => string '[email protected]' (length=17)

And want to pass it to javascript. My goal is to use this in a AJAX query.

So I did the following

var test = "<?php echo json_encode($test); ?>";
$.post("../path/to/file.php",
{
  test: test,
},
function(data,status)
{ 
  ...
});

But the following is triggering everytime

SyntaxError: missing ; before statement
var test = "{"1":"[email protected]","2":"test1@mail.
1
  • 1
    Maybe a missing semicolon after var test = "<?php echo json_encode($test); ?>" ? Your code example is not complete, there is no var input as stated in you error message. Commented Nov 10, 2015 at 15:21

1 Answer 1

3

Don't enclose the json output in quotes. It's unecessary:

var test = <?php echo json_encode($test); ?>;

json_encode() will already be adding any necessary " characters, and your extra " are breaking the syntax, e.g.

php:

$foo = 'ab"c';

json_encode($foo) -> "ab\"c";

js:

var test1 =  <?php echo json_encode($foo); ?>;
var test2 = "<?php echo json_encode($foo); ?>";

which comes out as:

var test1 = "ab\"c";      // this line is ok
var test2 = ""ab\"c"";  // this line is fubar
            ^--start string
             ^--end string
              ^^---undeclared/undefined variable
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.