Question

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?

Was it helpful?

Solution 2

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

?>

OTHER TIPS

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

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

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top