maverick6912
maverick6912

Reputation: 118

Download file using html returned from ajax call

I'm trying to download a file on the same page using html returned from the ajax call. The ajax call looks like this:

                            $.ajax({
                                url: './xyz.cshtml',
                                type: "POST",                               
                                data: {
                                    //some validation and data to send to server.
                                },
                                success: function (data, status, xhr) {
                                    //alert('status: ' + status + ', data: ' + data);
                                    var result = $(data);
                                    
                                    console.log(result);
                                    result.appendTo("body");
                                }
                             });

The html looks like this:

<iframe width='1' height='1' frameborder='0' src='http://server//some_folder/some.xlsm'></iframe> <script>document.body.style.cursor = 'default';</script>

Basically, I want to parse this iframe and then run it on the same page. When the code in iframe runs the file will download. So, I need help with parsing this html to page and then running this code block.

Thanks in advance.

Upvotes: 0

Views: 413

Answers (1)

Sumit Wadhwa
Sumit Wadhwa

Reputation: 3217

Alright, so first you wanna grab that src from the iframe, then create anchor dom element and just click that. I guess that should do the trick

var ajaxResponse = "<iframe width='1' height='1' frameborder='0' src='http://server//some_folder/some.xlsm'></iframe> <script>document.body.style.cursor = 'default';</script>";

// this function will simply download the file
function download(filename, dataurl) {
  var a = document.createElement("a");
  a.href = dataurl;
  a.setAttribute("download", filename);
  a.click();
}

var regex = /<iframe.*?src='(.*?)'/;
var src = regex.exec(ajaxResponse)[1]; // src from that iframe

download("SomeFileName.xmlsm", src);

Upvotes: 2

Related Questions