简体   繁体   中英

Wait till for completes using jQuery / Javascript

How can i make this code wait till the form gets a response. the form must submit to recurly and receive a response from recurly before it can go on.

if there is a way to assure there is a response would be nice kinda like success: or error:

$("#pay_window").dialog({
           autoOpen: false,
           width: 600,
            buttons: {
                "Submit Payment": function(){
                    $("#PaymentForm").submit();



                 <--- NEED A WAIT FUNCTION HERE --->



                    var dialogbox = $(this);
                    $.ajax({
                        url: "/payment",
                        data: $(this).find([company_id, billing_email, first_name, last_name, recurly_token, selected_plan, account]).serialize(),
                        type: "POST",
                        success: function (data) {
                            dialogbox.dialog("close");
                            alert('Payment Completed')

                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert('error: ' + textStatus + ': ' + errorThrown);
                        }
                    });
                    return false;
                }
            }
        });

A form submit is essentially the same thing as a post to the endpoint specified by the form's "action" attribute (or to the page containing the form). You could gather the form data and make a post (via jQuery to recurly) and then use jQuery's Deferred object methods ('then', 'done', 'fail', etc.) or use $.ajax and the success/error options...Granted this won't work in IE 7/8/9 (there's no access to a FormData object).

Given this rather over simplistic form:

<form id="foo" action="http://example.com/" method="POST">
    <input type="hidden" name="q" value="a">
</form>

One could grab the input and create a 'FormData' object:

var $foo = $('#foo'),
    formData = new FormData($foo[0]),


$.ajax({
    url: $foo.attr('action'),
    data: formData,
    type: "POST",
    success: function (data) {
        /* do what you want */},
    error: function (jqXHR, textStatus, errorThrown) {
        /* do what you've got to */ }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM