1

When I used jquery ajax to generate a excel file in server and return the file name, then I would like to handle the file name with other function.

However, there are several times, i.e 5s, to generate the excel file in server and not yet return back the file name.

During the 5s period, the script is still moving on and run other function, as the file name is not ready, other function became fail.

I would like to know how to run the other function when whole process of first function is done and return back the file name? Below code is what I did in current. Thank you.

<script>
$(".button").click(function(){
    var obj = {A:'A',B:'B',C:'C'};
    var file = "";
    file = genreport(obj);  //call ajax function to create excel file and return back the file name
    otherfunction(file);    //handle file name with another function 
});

function genreport(obj){
    var filename = "";
    $.post("getreport.cshtml", obj, //cshtml file will generate a excel file in server and return file name, i.e. report.xls
    function(data){
        console.log(data);
        filename = data;
    })
    .done(return filename);
}
</script>
Alpha Wong
  • 47
  • 4

2 Answers2

1

You can use 'async: false' as below :

$.ajax({
    type: "POST",
    url: url,
    async : false,
    data: data,
    dataType: dataType,
    success : function(data) {}
});

Or you can also use .then() on JavaScript Promise.

Devesh
  • 170
  • 11
1

OK so here you can pass the "otherfunction" as a callback to the ajax function

Something like this

genreport(obj, otherfunction)

And use it in genreport function like this

function genreport(obj, callback){ var filename = ""; $.post("getreport.cshtml", obj, //cshtml file will generate a excel file in server and return file name, i.e. report.xls function(data){ console.log(data); filename = data; callback(filename); //passing filename to callback }) .done(return filename); }

Gaurav Mall
  • 500
  • 4
  • 16