harmonickey
harmonickey

Reputation: 1419

Getting unexpected newline when inserting JavaScript with PHP

I am trying to insert items into a javascript array for the autocomplete function. I take the values that I need for the array from a database, so I grab them with PHP. Then I just push each item into the javascript array. However, it keeps telling me that I have an "unexpected token ILLEGAL" and it looks like it's pointing at the single "quote" character that gets inserted, then has a newline, then continues to the actual value.

My javascript/PHP

<script type="text/javascript">
        $(function() {
           var availableTags = [];
           <?php

              foreach ($modelList as &$model)
                 echo "availableTags.push('$model');" . "\n";
           ?>
           $("#devicemod").autocomplete({
                 source: availableTags
           });
        });


        </script>

Then the error message...

$(function() {
               var availableTags = [];
               availableTags.push('
***Uncaught SyntaxError: Unexpected token ILLEGAL***
ODEL: T]422P');availableTags.push('');availableTags.push('!');availableTags.push('!6.1/120{ MODEL: TM402P');availableTags.push('!A`$');availableTags.push('!DP1110   CREATED ON: JAN 29 2002');availableTags.push('!MODEL: TM402P');

It should turn out to be...

availableTags.push('ODEL:T]422P');
availableTags.push('');
etc...

Upvotes: 0

Views: 501

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173542

Using json_encode() you can do this in a single (and safe) step:

<script type="text/javascript">
$(function() {
   $("#devicemod").autocomplete({
       source: <?php echo json_encode($modelList); ?>
   });
});
</script>

The json_encode() function makes sure that the values are properly escaped according to the rules of JavaScript notation. This prevents nasty surprises when the values contain single quotes in this case.

If $modelList is not a true list (i.e. the keys are not numbered sequentially), you should apply array_values() first:

...
       source: <?php echo json_encode(array_values($modelList)); ?>
...

Upvotes: 1

Marc B
Marc B

Reputation: 360572

This is a bad idea:

   echo "availableTags.push('$model');" . "\n";

if $model contains ANY javascript metacharacters, particularly ', you'll introduce syntax errors and kill the entire <script> block. Never directly output arbitrary text into Javascript context - you're basically vulnerable to the JS equivalent of an SQL injection attack.

At bare minimum, you should be using json_encode() to guarantee that your text is syntactically valid for the context you're using it in:

echo 'availableTags.push(' . json_encode($model) . ");\n";

or better yet... why do all this pushing when youd could just generate an array automatically?

<?php
$data = array();
foreach ($modelList as $model) {
   $data[] = $model;
}
?>
var availableTags = <?php echo json_encode($data); ?>;

Upvotes: 1

Related Questions