0

I am getting an "Uncaught SyntaxError: Unexpected token ILLEGAL" error when try to load a page with a php variable.

$(document).ready(function() {
       $.get("index.html", {token:<?php echo $token; ?>}, function(data) {
                 //codes..
               });
 });

I can't seem to echo $token in my javascript and I am sure $token is valid.

Can someone help me solve this issue? Thanks a lot!

1
  • 4
    Is token a string? {token:'<?php echo $token; ?>'} Commented Aug 21, 2014 at 18:55

2 Answers 2

2

You're echoing text from PHP into a Javascript context, which means you have to generate valid Javascript code. Simplest solution: json_encode()

{token : <?php echo json_encode($token) ?>}

json_encode() will take care of any quoting/escaping which needs to be done.

e.g. if $token = 'foo', then you'd be producing

{token: foo}

and be producing an undefined variable error.

Sign up to request clarification or add additional context in comments.

Comments

1

you need to put quotes around the php output otherwise it will be treated as a javascript variable rather than a string

{token:'<?php echo $token; ?>'}

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.