-4
<!DOCTYPE html>
<html>
<body>
<input type="text" onkeypress="handleEvent(event)" name="FirstName" style="position: absolute; left: 50px;">
<script>
        function handleEvent(e){
           if(e.keyCode === 13){
                <?php 
                echo "hello";
                ?>
            }
        } 
</script>
</body>
</html> 

If I remove the PHP code in function and put alert("something") it works fine. But when I put an echo in PHP in function, "hello" is not displayed. Please help me, struggling from 2 days.

Sailesh Kotha
  • 1,939
  • 3
  • 20
  • 27

1 Answers1

2

PHP executes at runtime, your code creates something like this:

function handleEvent(e){
           if(e.keyCode === 13){
                hello
            }
        } 

echo is a php function which simple prints eveything inside "" into the markup. So just print with php what you else would write by hand:

function handleEvent(e){
           if(e.keyCode === 13){
                <?php 
                echo "alert(\"hello\");";
                ?>
            }
        } 

echo "alert(\"hello\");"; tells php to print alert("hello");. The \" makes sure echo prints the " character itself (because the string that echo needs to print is also written in ", so you need to escape additional ones, alternatively write echo 'alert("hello");';)

Alex
  • 9,911
  • 5
  • 33
  • 52