7

I am trying to submit a form through jquery. I want to get my form submit event get fired when jquery submits the form.

But when form is submitted successfully, submit event handler is not called successfully.

Below is the code :

<html>

<head>
<title>forms</title>

<script src="../common/jquery-1.6.2.min.js"></script>
<script>
$('#testform').submit(function() {
    $.post($(this).attr("action"), $(this).serialize(), function(html) {
        $("#menu").html('<object>'+html+'</object>');
    });
    return false; // prevent normal submit
});

</script> 

</head>

<body>

    <form id="testform" action="<%=getURL%>" method="post" >
        <!-- <input type="hidden" value="DocQrySetup" name=form>
        <input type="hidden" value="bdqdb1" name=config>-->
        <input type="hidden" value="test" name=otherParams>
    </form>

    <script language=javascript>
        $('#testform').submit();
    </script>

<div id="menu" style="position:relative; bottom: 0; overflow:hidden;">
</div>
</body>

I searched all the forums but was not able to get the resolution.

3
  • Why 2 different script referring .submit()?
    – Praveen
    Sep 11, 2013 at 6:47
  • The question is clear, and it's clear why it's not working... see @DaveForber answer below. Sep 11, 2013 at 6:47
  • hey @KshitijJain, you could mark this question as answered... :-) Sep 11, 2013 at 6:51

2 Answers 2

25

The form doesn't exist when you run the first script so your event handler has nothing to attach to.

Either need to move that handler to after the form or wrap it in

$(document).ready(function() { 
    $('#testform').submit(function() {
        /* your code */
    });
});
1
  • 6
    Mine is wrapped here and at the end and it still isn't firing. Sep 26, 2016 at 11:11
8

The form isn't defined when you attach the event listener, move the code where you attach the event listener after the form or wrap the code with:

jQuery(document).ready(function ($) {
    ...
});

And add a submit button.

...
<input type="submit" value="submit">
...
1
  • AMEN! This is totally the reason! And he should also get rid of this code: <script language=javascript> $('#testform').submit(); </script>, first, he doesn't have javascript in quotes and 2nd it is not needed, and ofcourse, $(document).ready does help Sep 11, 2013 at 6:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.