Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file through an ajax call php

I have a button and onclick it will call an ajax function.

Here is my ajax function

function csv(){      ajaxRequest = ajax();//ajax() is function that has all the XML HTTP Requests      postdata = "data=" + document.getElementById("id").value;      ajaxRequest.onreadystatechange = function(){         var ajaxDisplay = document.getElementById('ajaxDiv');         if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){             ajaxDisplay.innerHTML = ajaxRequest.responseText;                    }     }      ajaxRequest.open("POST","csv.php",false);     ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');     ajaxRequest.send(postdata); } 

I create the csv file based on the user input. After it's created I want it to prompt download or force download(preferably force). I am using the following script at the end of the php file to download the file. If I run this script in a separate file it works fine.

$fileName = 'file.csv'; $downloadFileName = 'newfile.csv';  if (file_exists($fileName)) {     header('Content-Description: File Transfer');     header('Content-Type: text/csv');     header('Content-Disposition: attachment; filename='.$downloadFileName);     ob_clean();     flush();     readfile($fileName);     exit; } echo "done"; 

But If I run it at the end of csv.php it outputs the contents of the file.csv into the page(into the ajaxDiv) instead of downloading.

Is there a way to force download the file at the end of csv.php?

like image 660
theking963 Avatar asked Jul 12 '11 17:07

theking963


People also ask

What is AJAX explain with example?

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


2 Answers

AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ....

like image 62
Marc B Avatar answered Oct 09 '22 02:10

Marc B


A very simple solution using jQuery:

on the client side:

$('.act_download_statement').click(function(e){     e.preventDefault();     form = $('#my_form');     form.submit(); }); 

and on the server side, make sure you send back the correct Content-Type header, so the browser will know its an attachment and the download will begin.

like image 24
blink281 Avatar answered Oct 09 '22 01:10

blink281