mcl
mcl

Reputation: 691

Javascript Syntax Error with embedded PHP code

I have made some silly error, but can not work out what I have done.

I am attempting to test passing variables from PHP to Javascript and if it is an array, json_encode it

My file is a PHP file ie .php

The php line of code that seems to be causing the error I have added to the original PHP and it works OK

<?php

$php_var = 'lol';
$php_array = array ();
$php_array["lady"] = "mary";
$php_array["gent"] = "joseph";
echo is_array($php_array) ? json_encode($php_array) : $php_array;  // same as faulty line in javascript
?>

<html>
<body>

<script type="text/javascript" charset="utf-8">

var php_var = "<?php if (is_array($php_var)) {echo json_encode($php_var); } else { echo $php_var;}; ?>";
document.write(php_var + ' ifElse<br>');

// THE FOLLOWING LINE GIVES  Uncaught SyntaxError: Unexpected identifier 
var php_var2 = "<?php echo is_array($php_array) ? json_encode($php_array) : $php_array; ?>";

document.write (php_var2 + ' EitherOR<br>');

alert(php_var + php_array);

</script>
<h1> Testing Jscript variables</h1>
</body>
</html>

Upvotes: 1

Views: 3935

Answers (3)

vedarthk
vedarthk

Reputation: 1333

As you have specified the error is at :

var php_var2 = "<?php echo is_array($php_array) ? json_encode($php_array) : $php_array; ?>";

The error may be due to your using double quotes ("") use single quotes ('') in Javascript.

This may solve your error : var php_var2 = '<?php echo is_array($php_array) ? json_encode($php_array) : $php_array; ?>';

Or you can directly create an Javascript Object from the JSON string using eval().

http://jsfiddle.net/jduGp/

Upvotes: 2

And Finally
And Finally

Reputation: 5704

I did it like this

<?php

$php_var = 'lol';
$php_array = array ();
$php_array["lady"] = "mary";
$php_array["gent"] = "joseph";
?>

<html>
<body>

<script type="text/javascript" charset="utf-8">

var php_var = <?php if (is_array($php_var)) {echo json_encode($php_var); } else { echo '"' . $php_var . '"';} ?>;
document.write(php_var + ' ifElse<br>');

// THE FOLLOWING LINE GIVES  Uncaught SyntaxError: Unexpected identifier
var php_var2 = <?php echo is_array($php_array) ? json_encode($php_array) : $php_array; ?>;

document.write (php_var2 + ' EitherOR<br>');

alert(php_var);

</script>
<h1> Testing Jscript variables</h1>
</body>
</html>

Not sure why you're trying to alert out php_array when Javascript isn't aware of that variable. You also don't need the quotes unless you're outputting a string. If you put quotes around an object Javascript will think it's a string.

Upvotes: 0

Techie
Techie

Reputation: 45124

Try this code. Replace the two lines as shown below.

var php_var = <?php if (is_array($php_var)) {echo json_encode($php_var); } else { echo $php_var;}; ?>;

var php_var2 = <?php echo is_array($php_array) ? json_encode($php_array) : $php_array; ?>;

Upvotes: 0

Related Questions