0

I am using the below code to call the javascript function from php script. Its not working while am adding the php variable in javascript($msg). Please help me to do this.

if ( isset($_GET['Error'])) {
    $msg =$_GET["Error"];
    echo '<script type="script.php">validate("Error",$msg);</script>';
}
3
  • <script type="script.php"> isn't a valid value for the type attribute. Change script.php Commented Jan 17, 2014 at 4:07
  • echo '<script type="script.php">validate("Error",$msg);</script>' can't call a php script. It should read something like <script >validate("Error",$msg);</script> but I'd have to know what the validate function does to be sure anyway, you should leave the type attr off. it's assumed now, but if you had to it's type="text/javascript" Commented Jan 17, 2014 at 4:08
  • <script >validate("Error",$msg);</script> not working for me. Commented Jan 17, 2014 at 4:09

2 Answers 2

1

You have to quote the $msg or it will be syntax error in javascript. And the type is non sense.

Since the msg is from the $_GET, don't forget the escape it.

if ( isset($_GET['Error'])) {
    $msg =$_GET["Error"];
    echo '<script>validate("Error", "'.htmlspecialchars($msg).'");</script>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

not good enough, though. by default it'll let ' go through unencoded and STILL break the JS syntax. json_encode(htmlspecialchars(...)) would do the trick.
@MarcB Even the ' is quoted by "?
0

Instead of an inline script, this should work:

<html>
    <head>
        <script type="text/javascript">
            function testMe(x){
                alert(x);
            }
        </script>
    </head>
<body>
<?php
    $phpVar = 'I am a PHP variable';

    echo "<a href=\"#\" onclick=\"javascript:testMe('" . $phpVar . "');\">Click Me</a>";
?>
</body>
<html>

Comments

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.