how do make waiting for ajax to complete

Tags: , ,



I newbie. I have a function application for employment (apply-job).What I do is submit the request with an ordinary link, with a click-function applied on it but processing time is quite long. I want disable “#apply-job” avoid click too much or disable window and fade for ajax to complete. Thank. My JS:

$("#apply-job").click(function() {
        if($('#jobcandidate-name').val() != '' && $('#jobcandidate-email').val() != '' && $('#jobcandidate-phone').val().length >= 10 && $('#jobcandidate-address').val() != '' &&  ($("input[name='CandidateAttachment[2][fileAttachment][path]']").val() != undefined || $('#jobcandidate-curriculum_vitae').val() != '') ){
            let data = $('#apply-job-form').serialize();
            let roleArticle = $('.show_new_role :input').serialize();
            if ($('#apply-job-form').find('.has-error').length){
                swal("Thử lại", "Vui lòng kiểm tra lại thông tin!", "error");
            } else {
                $.ajax({
                    url: '$urlRequest',
                    type: 'POST',
                    dataType: 'html',
                    data : data + '&' + roleArticle
                }).done(function(result) {
                    response = JSON.parse(result);
                    if (response.type == "success"){
                        let checkReload = swal("Thành công", "Cảm ơn bạn đã ứng tuyển!", "success");
                        checkReload.then(function() {
                            location.reload();
                        });
                    }
                });
            }
        } else {
            if ($("input[name='CandidateAttachment[2][fileAttachment][path]']").val() == undefined && $('#jobcandidate-curriculum_vitae').val() == '') {
                $('#jobcandidate-curriculum_vitae').parents('.form-group').find('.txt-lable').css('color','red');
                $('#jobcandidate-curriculum_vitae').parents('.form-group').find('.show_error2').text('* Không được bỏ trống');
            }
            swal("Thử lại", "Vui lòng kiểm tra lại thông tin!", "error");
        }
    });

Answer

ajax has await option. You can use it to make the execution wait till the ajax all is done. Make sure you combine it with async which will tell there’s an asynchronous step in the function. See below snippet

$("#apply-job").click(async function() {
  ......
  await $.ajax({
  ......
});

Update: to make sure the click is disabled while ajax is working, add a disabled attribute and assign the click only when the attribute is not present. Clear the attribute once process is complete.

$("#apply-job:not([disabled])").click(async function() {
  $("#apply-job").attr("disabled","disabled")
  ......
  await $.ajax({
  ......
  $("#apply-job").remoeAttr("disabled")
});


Source: stackoverflow