jQuery form post before submit

2019-08-02 15:16发布

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!

标签: jquery forms
3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-02 15:33

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);
查看更多
家丑人穷心不美
3楼-- · 2019-08-02 15:37

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>
查看更多
Fickle 薄情
4楼-- · 2019-08-02 15:38

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/

查看更多
登录 后发表回答