Wickethewok
Wickethewok

Reputation: 6710

jQuery form post before submit

I have a page with a form on it that needs to post to an external URL. However, I also need this information to be sent to the current page (mypage.php). For security reasons, I cannot just post to mypage.php and use cURL to post via PHP to the external site - the form has to submit directly to the external site.

This code would be found on mypage.php and does not work (I assume that the submit of myform is not waiting for post):

$('#myform').submit(function() {
    $.post('mypage.php', serialized_form, 
        function(data) {
            ...
        }, 'html'
    );
}

...

<form id="myform" action="http://example.org" method="post">
...
</form>

What is the best way to do something like this?

Thanks!

Upvotes: 1

Views: 5272

Answers (3)

fresskoma
fresskoma

Reputation: 25781

If I understood your problem, then you need to your data to $url and still submit the form afterwards. Hope the following code works for you (not tested^^):

;(function($) {
    var sent = false;

    $('#myform').submit(function() {
        if(sent) {
            return true;
        }

        $.post('mypage.php', serialized_form, 
            function(data) {
                sent = true;
                $('#myform').submit();
            }, 
            'html'
        );

    return false;
    });
})(jQuery);

Upvotes: 0

a1ex07
a1ex07

Reputation: 37354

Will it work for you?

$('#myform').submit(function() {
$.post('mypage.php', serialized_form, 
    function(data) {
        ...
       $.post('http://example.org', serialized_form, ....);
    }, 'html'
);
return false;
}

<form id="myform" method="post">...</form>

Upvotes: 0

Seaux
Seaux

Reputation: 3517

you can make the $.post() sync, which would block the javascript (and site) from continuing until its returned.

If you use $.ajax({type: 'post', async: false}) (plus your other params) that should do the trick.

You can read more info @ http://api.jquery.com/jQuery.ajax/

Upvotes: 5

Related Questions