FlyingCat
FlyingCat

Reputation: 14250

Simple Javascript error

I got a syntax error on the following code. Once I took out the first line of code, the alert pops. My brain is almost dead and I can't find out why. Please help. Thanks a lot.

JS

var rss = <?php echo json_encode($test); ?>;

alert("Hello World");

Updated

html

  <?php 

    $test=get_array(); 

   //the $test is a multi-dimention array.

  ?>


<script type="text/javascript" src="js/slideshow.js"></script>

Upvotes: 2

Views: 163

Answers (4)

Krishna
Krishna

Reputation: 353

In a .js file, PHP doesn't work. It will work only in files with extension .php . Put your JS code in the PHP page; then it works.

Upvotes: 1

Blaster
Blaster

Reputation: 9110

To avoid error, your code should be:

var rss = <?php echo json_encode($test) ? json_encode($test) : "''"; ?>;
alert("Hello World");

Even if json_encode returns false, your code would be:

var rss = '';
alert("Hello World");

Upvotes: 2

xdazz
xdazz

Reputation: 160833

json_encode will return FALSE on failure, so if it fails, echo false will output nothing.

so your code became below, which give you a syntax error.

var rss = ;

alert("Hello World");

Edit: From your updated edit, the reason is: You can not write php code in a js file.

If you need that variable in the js file, assign it to a global variable first.

<script type="text/javascript">
  var rss = <?php echo json_encode($test); ?>;
</script>
<script type="text/javascript" src="js/slideshow.js"></script>

Upvotes: 5

Yang
Yang

Reputation: 8701

This is because JavaScript throws fatal error and stops current script execution because of:

var rss = <?php echo json_encode($test); ?>; 

The problem is that this may return non-Valid JSON string and it throws new exception,

What you can do:

First of all you should determine if the string you got from PHP is actually valid. As JSON methods usually do throw errors, you can simply put this var into try/catch block

try {

  var rss = <?php echo json_encode($your_array); ?>;

} catch(e){

  alert('Invalid JSON string');
}

In PHP, please also check if it's valid to prevent sending invalid JSON string back to javaScipt

Upvotes: 1

Related Questions