0

I'm executing some javascript functions from php using the following:

echo '<script language="javascript" type="text/javascript">window.top.window.updateLog("fornecedores","'.$errorMsg.'");</script>';

The problem is that sometimes $errorMsg has some " what make it syntax incorrect. What should I do?

Thanks

metRo_
  • 435
  • 1
  • 5
  • 17
  • 1
    Please stop doing this! This would be a perfect use case for Ajax. Any future developer working on your code will thank you forever if you do. – Undefined Jun 19 '13 at 16:32

3 Answers3

1

I would do this way:

echo '<script language="javascript" type="text/javascript">window.top.window.updateLog("fornecedores",'.json_encode($errorMsg).');</script>';

I made research about inserting PHP values to JS code.
As result - I found that using json_encode() is most perfect way.
For many reasons.

Bogdan Burym
  • 5,475
  • 2
  • 25
  • 46
-1

Escape the " with addslashes($errorMsg). http://php.net/manual/en/function.addslashes.php

Havsmonstret
  • 847
  • 6
  • 13
-1

you should use the heredoc syntax in order to echo other scripts as strings correctly:

echo <<<ADF

<script language="javascript" type="text/javascript">

window.top.window.updateLog('fornecedores','$errorMsg')

</script>

ADF;

here is the documentation link:http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc