Question

To learn about web programming, I'm trying a simple html/javascript/php "product search" page. Here is the index.php file:

<html>
    <head>
        <title>Product Search</title>
        <script type="text/javascript">
            function mySubmit() {
                alert("submitting...");
                var product_type = $('product_type').value;
                $.post('product_search.php', { product_type: product_type }, function (data) {
                    alert("result = " + data); 
                    $('body').html(data);
                }
                return false;
            }
        </script>
    </head>
    <body id="body">
        <script type="text/javascript">
            mySubmit();
        </script>
        <form class="form" id="myform" method="post" onsubmit="javascript:return mySubmit();">
            Product Type:
            <input id="product_type" type="text" name="product_type"/>
            <br/><br/>
            <input id="submit" type="submit" value="Submit"/>
        </form>
    </body>
</html>

and the product_search.php file is very small:

<?php


$product_type = $_POST["product_type"];
echo "<h1>$product_type</h1>";

?>

The problem is that it seems like the onsubmit event is never called for the form. I thought it was a JavaScript problem (as in, not allowed to run), but if I run an alert instead of calling mySubmit() when the onsubmit event is called, it works!

Also, am I wrong in thinking that the JavaScript just under the <body id="body"> should be run? It is never run either.

So, for those who didn't read all that: why is my JavaScript function not being run when the onsubmit event is fired?

Was it helpful?

Solution

I get the following parsing errors when I run your code:

Uncaught SyntaxError: Unexpected token return

Uncaught ReferenceError: mySubmit is not defined 

You are missing the closing ) on your $.post call, which is breaking the parser. Once you fix that, you'll get the $ is undefined error until you reference jQuery.

http://jsfiddle.net/Z6hJK/

OTHER TIPS

<script type="text/javascript">
            mySubmit();
        </script>

above function is called but when it is called, even document.getElementById('product_type').value gives error (which might not be enabled on your browser to catch) as it product_type turn out to be null as javascript in body gets executed before browser has fully rendered the page. The moment it is getting called, product_type is not yet rendered.

On click also your function is getting called, but this time may be it is failing as you do not have reference to Jquery. include one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top