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 . ';';
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help @Serg - you're outlined method works just fine!
1

Do this instead:

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

Comments

1

I have not tested this but give it a try:

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

Comments

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

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.