Mike
Mike

Reputation: 1738

Jquery Wait Until AJAX Call is Done

I have an ajax function for saving a forms data. I want it to remain asynchronous because the users can hit save any time. However, I have another function that converts the form to a PDF and I want it to run the save function before creating the PDF (in case the users have added more data). Is there a way to make $('input.submit') wait for save to finish before opening the pdf? Below is the jQuery I am using:

$("button#save").on('click', function (){
                $.ajax({
                    type: 'POST',
                    url: '<?php echo matry::base_to('utilities/crm/field_day_save');?>',
                    data: $("form#trip_form").serialize(),
                    dataType: 'json',
                    success: function (data)
                    {
                        $("#alerts").html(data.alert);
                        $("#form_id").val(data.id);
                    }
                    });
            });
        $("input.submit").on('click', function(event){
            event.preventDefault();
            $("button#save").trigger('click');
            window.open('<?php echo matry::base_to('custom_worddocs/field_day');?>' + '&fd_id=' + $("#form_id").val());
        });

In short, I want $('button#save').click() to remain asynchronous, but I want $(input.submit) to wait for button save to complete before opening new window.

Upvotes: 2

Views: 3819

Answers (2)

Kevin B
Kevin B

Reputation: 95064

Have your click handler return a promise object, then use triggerHandler() to trigger the click event and get it's return value.

$("button#save").on('click', function (){
    return $.ajax({
        ...

and

...
$("button#save").triggerHandler('click').done(function(){
    window.open(...);
});
...

Proof of concept: http://jsfiddle.net/SRzcy/

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 220126

jQuery's ajax function returns a jqXHR object which, among other things, behaves like a deferred.

By only calling window.open from within the then function, it'll wait for the AJAX to complete:

$("button#save").on('click', function () {

    var jqXHR = $.ajax({ /* your config... */ });

    $("input.submit").one('click', function(event) {
        event.preventDefault();
        $("button#save").trigger('click');

        jqXHR.then(function () {
            window.open('<?php echo matry::base_to('custom_worddocs/field_day');?>' + '&fd_id=' + $("#form_id").val());
        });
    });

}

Upvotes: 4

Related Questions