user2429082
user2429082

Reputation: 485

Download zip file with jquery from ajax post request

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?

Upvotes: 6

Views: 30841

Answers (3)

Steve
Steve

Reputation: 20469

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>');

});

Upvotes: 3

Mikk
Mikk

Reputation: 2229

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();

Upvotes: 15

Canser Yanbakan
Canser Yanbakan

Reputation: 3870

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));

?>

Upvotes: 13

Related Questions