0

I am currently displaying javascript via PHP echo:

        echo 'var currentInvoiceDataJSON = <?php echo json_encode($yearData_Invoices[$currentYear] ); ?>;';

However I get a Uncaught SyntaxError: Unexpected token < error which I infer is related to the second

How can I get this resolved and there any other possibilities?

Some expert advise would be appreciated.

0

4 Answers 4

5

That code ends as invalid Javascript code.

Here's what happens:

Your server echoes a string:

echo 'var currentInvoiceDataJSON = <?php echo json_encode($yearData_Invoices[$currentYear] ); ?>;';

Your browser now has:

var currentInvoiceDataJSON = <?php echo json_encode($yearData_Invoices[$currentYear] ); ?>;

Once your PHP script finishes running and echoes that first string, PHP cannot process the inner echo.


What I would do:

$data = json_encode($yearData_Invoices[$currentYear]);
echo 'var currentInvoiceDataJSON = ' . $data . ';';
1
  • Thanks for your help @Serg - you're outlined method works just fine!
    – nickyfsh
    May 10, 2013 at 3:46
1

Do this instead:

echo 'var currentInvoiceDataJSON = '.<?php echo json_encode($yearData_Invoices[$currentYear] ); ?>.';';
1

I have not tested this but give it a try:

echo "var currentInvoiceDataJSON = '".str_replace("'","\\'",json_encode($yearData_Invoices[$currentYear]))."';";
1

just change to

echo "var currentInvoiceDataJSON = ".json_encode($yearData_Invoices[$currentYear] ).";";

and also be aware that single quoted strings in php don't interpolate variables so

$a = "Hello World";
echo '$a'; // outputs :  $a
echo "$a"; // outputs :  Hello World

and when you are in a php context

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.