How to check ajax response before the request is considered completed in CakePHP 3.x?

时间:2015-12-10 01:58:33

标签: jquery ajax cakephp cakephp-3.1 cakephp-3.x

I have been trying to add two users (one at a time) and then pay using stripe. I originally thought the problem lied in the fact that ajax is asynchronous, posting both user forms at the same time, but I now believe it is because when I get the response from the operation, the ajax operation is considered completed and it moves onto the other operations.

The response has the validation errors with it and I am using a jQuery function that adds the errors to the form and that form doesn't get submitted until the errors are fixed.

This is a major issue because the two users are to be linked by a group_id that is the same value as the id of the primary user (user #1). If user #1 had validation errors and user #2 doesn't, user #2 gets added and therefore cannot be linked to user #1's id value since it doesn't exist yet.

I can do a work around with a hidden form field on each user form that has matching values for group_id and then update the data once user #1 gets added, but I would love to be able to check the response for errors before the ajax operation is completed. Is there any way to do this?

My Ajax function:

function submitFormAjax(formData) {
    if (formData.length) {
        var formId = formData.attr('id');
        if ( $('#'+formId ).hasClass('disabled') ) {
            console.log('form is disabled don\'t post data');
        } else {
            return $.ajax({
                type: formData.attr('method'),
                url: formData.attr('action'),
                data: formData.serialize(),
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                }
            })
            .done( function( data ) {
                addFormErrors(formId, data);
            })
            .fail(function( data ) {
                console.log('user\(s\) could not be added');
                console.log( data );
            });
        }
    }
}

Submitting Forms Function:

function submitAllForms() {
    // wait until both of the other forms' data are submitted
    $.when( submitFormAjax($('#userForm')), submitFormAjax($('#secondUserForm')) ).then(
        function() {
            if ( $('.error-message').length ) {
                $form.find('button').prop('disabled', false);
            } else {
                $('#payment-form').get(0).submit();
            }
    });
}

I don't believe you need to see the function where it adds the errors as that functionality works fine. Just know that they are added with the addFormErrors() function.

0 个答案:

没有答案