Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert PHP code snippet in javascript

Tags:

javascript

php

my code-

<?php
session_start();
$_SESSION['errors']="failed";
?>


<head>

    function myfunc()
    {        
         alert(<?php echo $_SESSION['errors']; ?>);
    }
</head>

<body onload="myfunc();">

but alert msg is not popping up.

like image 301
nectar Avatar asked Dec 18 '22 00:12

nectar


2 Answers

Two errors in your code:

  • You are missing <script> tags
  • You are missing single/double quotes in alert

Try this:

<?php
session_start();
$_SESSION['errors']="failed";
?>


<head>

<script>
    function myfunc()
    {        
         alert('<?php echo $_SESSION["errors"]; ?>');
    }
</script>
</head>

You might want to put the myfunc() in window.load event or some click event to test it. Additionally, as rightly suggested by ThiefMaster, you may want to use the addslashes function for the $_SESSION["errors"] in the alert.

Note: It is assumed that file extension for your code is php.

like image 97
Sarfraz Avatar answered Dec 28 '22 19:12

Sarfraz


PHP will just print out failed, it won't print out the string delimiters along with it, so make sure you put them in:

function myfunc()
{        
     alert("<?php echo $_SESSION['errors']; ?>");
}
like image 41
Andy E Avatar answered Dec 28 '22 19:12

Andy E