0

I've created a form with html being echoed in PHP and am trying to call a Javascript function in the same form. I've copied and pasted the js part which I have put in my head tags at the top of the php file.

<script>
    function validate(){
        alert("You need to enter the date in format dd-mm-yyyy");
    }
</script>

Further on I have this at the start of the form

echo "<form method=\"post\" action=\"index.php\" onsubmit=\"validate()\">
        <br>
        <span>Name: <input type=\"text\" name=\"name\" value=\"$name\"></span>"

Is it possible to call javascript from php in the same document? Cheers

3
  • calling JavaScript function inside PHP (in server side) is like to call undefined function, but if you mean calling the function in client side, then yes you can Commented Mar 10, 2013 at 18:55
  • Is better if you do an ajax control Commented Mar 10, 2013 at 18:56
  • @Akam The thing is I use PHP to create a form if a button is clicked because it processes using the same file. Commented Mar 10, 2013 at 18:57

3 Answers 3

1

you have to try this inside php code ..

       echo "<script type='text/javascript'>
        function validate(){
         alert('You need to enter the date in format dd-mm-yyyy');
                        }
     </script>";

Hope it use-full fro you..

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

Comments

0

For the sake of argument, you tried moving your script to the bottom of your page?

echo ... validate()
...
<script>function validate()</script>

Comments

0

You need to make your function available when it is executed.

window.onload = function() {
    function validate(){
        alert("You need to enter the date in format dd-mm-yyyy");
    }
};

Comments

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.