Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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>';
}
share|improve this question
    
<script type="script.php"> isn't a valid value for the type attribute. Change script.php –  Aaron W. Jan 17 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" –  ZombieBunnies Jan 17 at 4:08
    
<script >validate("Error",$msg);</script> not working for me. –  user3085540 Jan 17 at 4:09

2 Answers 2

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>';
}
share|improve this answer
    
+1 for htmlspecialchars($msg). –  JJPA Jan 17 at 4:13
    
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. –  Marc B Jan 17 at 4:32
    
@MarcB Even the ' is quoted by "? –  xdazz Jan 17 at 4:39

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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.