1

I'm getting this error in Firebug :

SyntaxError: unterminated string literal

Panel_Measurements[i] = "<br />

And now all off my functions fail to work... I've tried multiple solutions, but none of them work... this is my code :

<script type="text/javascript" language="javascript>
   <?php
      $i = 0;
      while(isset($dbPanel_Name[$i]))
      {
   ?>

          Panel_brand_type[i]   = "<?php echo addslashes($dbPanel_Brand_Type[$i]); ?>";
          Panel_description[i]  = "<?php echo addslashes($dbPanel_Description[$i]); ?>";
          Panel_measurements[i] = "<?php echo addslashes($dbPanel_Measurements[$i]); ?>";
          Panel_warranty[i] = "<?php echo addslashes($dbPanel_Warranty[$i]); ?>";
          i++;
   <?php
         $i++;
       }
    ?>
</script>

If there's any other way to get PHP variables into Javascript, I would love to know! Any type of help is usefull to me.

Sincerly,

Harmen Brinkman

1 Answer 1

6

A much better way of injecting string literals (and pretty much every other type of value too) in JavaScript is json_encode:

Panel_brand_type[i] = <?php echo json_encode($dbPanel_Brand_Type[$i]); ?>;

Note that I removed the double quotes around the PHP tags, json_encode provides them itself.

The only potential issue with this solution is that the string you are injecting has to be UTF-8, but your existing code with addslashes also had a similar problem (it blindly assumes that you are using a single-byte encoding) so IMHO there's no regression.

Finally, make sure that the PHP variables are actually set before trying to access them! If there is no such variable, PHP will spew out its warnings where JavaScript code is expected: a sure way to ruin your day.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help, but when I don't add double quotes Fire bug gives an syntax error of missing quotes, and when I do add them it gives a Syntax error like this : Panel_brand_type[i] = "" value ""; Any suggestions?
@HarmenBrinkman: If the variables exist in PHP there is nothing else that could cause a JS error (even if the string is not UTF-8, that will result in a null value instead of an error). So the only logical explanation is that you are injecting the values of variables that don't exist.
For some reason it does work now, without extra saving or other changes, I will markt this one as the answer! thank you very much!

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.