user3085540
user3085540

Reputation: 295

Call javascript function using php variable

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>';
}

Upvotes: 0

Views: 149

Answers (2)

Eric
Eric

Reputation: 1020

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>

Upvotes: 0

xdazz
xdazz

Reputation: 160833

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>';
}

Upvotes: 1

Related Questions