luca
luca

Reputation: 3318

Know the result of a ajax call from another function in javascript

I have a function uploadFunction that upload file on my server through Rest web service called with JQuery ajax. I use this method also for another function and I need to know the result of web service call to create or less one row with the name of the file that has been uploaded.
The actual approach with the variable doesn't work, is there a way to know if the file is correctly uploaded? I tried with async: false (because I anyway wait the upload) but my waiting modal appears and the end of upload and not immediately.

function uploadFunction(fileType){
//CSRF attribute for spring security
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

var formData = new FormData();
var fileControl = document.getElementById(fileType);
var length = fileControl.files.length;
for(var i = 0; i< length; i++){ 
    formData.append('file[]',fileControl.files[i]); 
} 
formData.append('idFleet', selectedFleet);
formData.append('idCar', $("#selectedCar").val());
if(fileType!='dat')
    formData.append('initialKm', 0);
else
    formData.append('initialKm', $("#initialKm").val());
jQuery.ajax({
    url : 'upload',
    type: 'POST',
    contentType: false,
    processData: false,
    data:formData,
    beforeSend:function(xhr) {
        xhr.setRequestHeader(header, token);
        waitingModal.showPleaseWait();
    },  
    success: function(data,status,xhr){
        //No exception occurred
        if (data.status){   
            //Also the field are right(for e.g. form value)
            if(data.success){
                //Store information if file is datatable
                if (fileType=='datatable')
                    $("#datatablePath").val(data.result[0]);
                notifyMessage(fileType + " has been uploaded!", 'success');
                uploadResult=true;
            }
            else{
                //code if there are some error into form for example
            }
        } else {
            notifyMessage(data.result, 'error');
            $('#acquisitionWizard').bootstrapWizard('show',2);//show
            uploadResult=false;
        }
    },
    error: function(xhr,status,e){
        window.location.href = "/ATS/500";
    }
}).complete(function() {
    //add timeout because otherwise user could see a too fast waiting modal
    setTimeout(function(){
        waitingModal.hidePleaseWait();
    }, 1000);
    });
}

My function that call uploadFunction is this:

$(function() {
    $("#addDatButton").click(
            function() {
                var fileControl = document.getElementById('dat');
                if (fileControl.files.length!=0 && $('#initialKm').val().length == 0){  
                    notifyMessage("You have to add initial Km!", 'info');
                }else if (fileControl.files.length==0 && $('#initialKm').val().length != 0){    
                    notifyMessage("You have to add dat file!", 'info');
                }else if (fileControl.files.length==0 && $('#initialKm').val().length == 0){    
                    notifyMessage("You have to add dat file and initial Km!", 'info');
                }else{
                    uploadFunction('dat');
                    if (uploadResult){
                        datUpload=true;
                        var fileName=document.getElementById('datName').value;
                        var fileUploadHTML='<div class="row"> <div class="col-xs-4"><div class="form-group has-success"><div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-upload" style="color: green"></i></span> <input type="text" class="form-control" readonly="readonly" placeholder="'+fileName+'"></div></div></div><div>';
                        $("#fileUploadSuccess").append( fileUploadHTML );
                        document.getElementById("initialKm").value = '';
                        document.getElementById("dat").value = '';
                        document.getElementById("datName").value = '';
                    }
                }

            });
});

Upvotes: 0

Views: 45

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

Use promises. Just return the ajax promise (its return value) from uploadResult() and add the followup code inside an .then or .done call:

e.g.

function uploadFunction(fileType){
    [snip]
    return jQuery.ajax({

and use like this:

uploadFunction('dat').then(function(uploadResult){
     if (uploadResult){
         [snip]
     }
});

Never use async: false. It blocks the browser from any other processing. Always work with async operations.

Upvotes: 3

Related Questions