Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download zip file with jquery from ajax post request

Tags:

jquery

ajax

php

I would like to know if it's possible to do an ajax post request to a specific url and receive in data a zip file in only on request? Or I have to send two requests... one, in order to have the url of the zip file inside the server which has been created and an another to download the zip file?

like image 405
user2429082 Avatar asked May 15 '14 11:05

user2429082


People also ask

Can we download file using Ajax?

Downloading PDF File on Button Click using jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).

How does .post work in jQuery?

jQuery $.post() Method The $.post() method requests data from the server using an HTTP POST request. Syntax: $.post(URL,data,callback); The required URL parameter specifies the URL you wish to request.


3 Answers

Sure you can do this! But only new browsers support this.

var url = 'test.zip';
var filename = 'test.zip';
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'blob';
request.onload = function() {
   var link = document.createElement('a');
   document.body.appendChild(link);
   link.href = window.URL.createObjectURL(request.response);
   link.download = filename;
   link.click();
};
request.send();
like image 88
Mikk Avatar answered Nov 05 '22 15:11

Mikk


The native answer is no!

But you can do like this.

Your ajax request:

$.ajax({
    url: 'your-url-that-gives-zip-file.php',
    dataType: 'JSON',
    success: function(response){
        if(response.zip) {
            location.href = response.zip;
        }
    }
});

Your php file:

<?php

//Get your zip file code with and combine with http://youradress.com

$zipFile = 'http://youraddress.com/downloads/'.$zipFile;

echo json_encode(array('zip' => $zipFile));

?>
like image 36
Canser Yanbakan Avatar answered Nov 05 '22 16:11

Canser Yanbakan


You cant download a file with ajax.

If you only want one request, then ditch the ajax and append a hidden iframe to the page, with the php file as its source.

This will limit you to a get request though.

eg:

$('#id').click(function(){

    $(body).append('<iframe style="display:none;" src="yourfile.php?key=value"></iframe>');

});
like image 3
Steve Avatar answered Nov 05 '22 14:11

Steve