0

I have this piece of code into my php file:

<?php
if(isset($_POST['submit'])){
     if($_POST['email'] != ''){
           $email = $_POST['email'];
           $query = "INSERT INTO user(email) VALUES('". $email . "')";
           $stmt = $db ->query($query);
           if($stmt){
                 echo "<script>displayPopup('success')</script>";
           }else{
                echo "";
           }
      }
  }
?>

My JS file is included before the closing tag and it's well charged. But I have error saying the function displayPopup is not defined

Any idea ? :(

4
  • 1
    try moving your displayPopup function to the top of the page just before the </head> tag. Commented Apr 28, 2017 at 11:42
  • If you know jQuery check the $(document).ready(); function Commented Apr 28, 2017 at 11:42
  • The JS file needs to be included before the call to displayPopup Commented Apr 28, 2017 at 11:45
  • Show where the function is defined. You also are open to SQL injections. Commented Apr 28, 2017 at 11:51

1 Answer 1

1

The main problem as far as I can tell is that the displayPopup function is being defined at the end of your document.

PHP being server-side and JS being client side, the conditions for echo'ing your script occur before the javascript is loaded/read.

This means that at the moment of that script being executed, the "displayPopup" function does not, in fact, exist.

Quickest way to test is to add the following code just before the end of your < /head> tag:

<script type="text/javascript">
    function displayPopup(msg){
        alert(msg);
    }
</script>

You can always obviously replace that function with whatever your actual displayPopup function is. An alternative to this is to use Ajax to submit your forms for a more seamless experience but the above should fix your issue.

I hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

alternatively you can just add the complete js file before the end of the </head> tag instead of putting it at the end of the document, but this may impact page load times

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.