asehgal asehgal - 5 months ago 8
JSON Question

Cant echo PHP variable inside <script> tags?

This is my PHP code. I want error to be displayed using an alert window.

if ($projectid=="")
{
$error = 'You must choose a project.
Click &lsquo;back&rsquo; and try again.';
include error.html.php';
exit();
}


This is error.html.php that is supposed to be parsed by the browser

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">


</head>

<body>

<script>
var error = <?php echo $error ; ?>;
window.onload = function(){ alert(error); }
</script>
</body>
</html>


Wahts up with the script tags ? Do they prevent PHP from running ?

Answer

Your problem is that javascript is run on the client and will run after the page loads and so after the php is run on the server.

However, you can do something like the following which allows php to set the value of a javascript variable when the page loads and then AFTER the page is loaded runs the javascript to display the message.

<?php 
$error = "test me";
echo "<script>error = '" . $error  . "'</script>";
?>

<script>
var error;
window.onload = function(){
    alert(error);
}

</script>

UPDATE Based on your edits, here's an updated answer. The echo "<script>error = '" . $error . "'</script>" is needed to assign the $error to the javascript variable when the page is loaded.

if ($projectid=="")
  {
    $error = 'You must choose a project.
              Click ‘back’ and try again.';
    echo "<script>error = '" . json_encode($error)  . "'</script>"
    include error.html.php';
    exit();
}

And the html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Script Error</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">


    </head>

    <body>

         <script> 
             var error;
              window.onload = function(){ alert(error); }
         </script>
    </body>
</html>