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?
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).
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.
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();
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));
?>
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>');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With