Run
Run

Reputation: 57176

How to enable or trigger the submit event after ajax post

How can I enable or trigger the submit event after ajax post?

For instance I have this form I don't want to submit it yet,

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">

<input type="hidden" name="item_name_1" value="Book 1" />

...

<input type="submit" name="pay" value="Check Out" />

</form>

until this page is called - session_end.php,

unset($_SESSION[SESSION_CART]);
unset($cart);

jquery,

$("input[name=pay]").click(function(){
    $("#form-paypal").submit(function(){

        $.post('re_post.php', {}, function() {

                        // I get eternal loop if I use either of these lines below,
            //$("#form-paypal").trigger('submit');
            //$("#form-paypal").submit();

        });


        return false;
    })
}); 

I will get the eternal loop on this page re_post.php but the form is not submitted.

Upvotes: 0

Views: 252

Answers (2)

Halcyon
Halcyon

Reputation: 57709

When you click a submit button the submit even for a form is fired.

What you're doing now is weird. Everytime you click the submit button, you add another submit handler (which does ajax and then calls submit again?)

Attach the submit handler on page load, once.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You don't really need the $("input[name=pay]").click handler. A simple .submit() event handler registration should be sufficient.

As far as your infinite loop problem is concerned you could append .data() to the form to track status and avoid the infinite loop:

$(function() {
    $('#form-paypal').submit(function() {
        if (!$(this).data('valid')) {
            // we are entering here the first time we try to submit
            $.post('re_post.php', { }, function() {
                // we set the data so that when we trigger the submission we 
                // don't perform any more AJAX requests and avoid the infinite loop
                $('#form-paypal').data('valid', true).submit();
            });
            return false;
        }
        return true;
    });
});

Upvotes: 2

Related Questions