nickyfsh
nickyfsh

Reputation: 175

PHP echo javascript with PHP variable

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.

Upvotes: 0

Views: 4191

Answers (4)

Orangepill
Orangepill

Reputation: 24645

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

Upvotes: 1

Danny
Danny

Reputation: 1185

I have not tested this but give it a try:

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

Upvotes: 1

drum
drum

Reputation: 5651

Do this instead:

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

Upvotes: 1

sergserg
sergserg

Reputation: 22264

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 . ';';

Upvotes: 5

Related Questions