Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file with an ajax call

I am using PHPExcel to read an excel template, populate the data, and ask the user to download the file.

generate_excel.php

$objPHPExcel = PHPExcel_IOFactory::load("./template.xlsx");
//populate data ...
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');

When I open generate_excel.php directly from the browser, the result file is downloaded. But if I make an ajax call to the generate_excel.php, I don't get the download prompt. Using chrome developer tools, I can see from the Network tab that the ajax call was successfully completed and a bunch of random characters is seen in the response data. I'm assuming that is the excel object.

Does anyone know how I can achieve the download excel feature using ajax? I don't want to refresh the page. When the user clicks on the "export" button, there should be an ajax call to the php file and prompt the user to download.

Thanks!

like image 541
John Ng Avatar asked Jun 27 '13 18:06

John Ng


People also ask

Can we download file using Ajax?

We cannot download the file through Ajax, must use XMLHttpRequest.

How can I download Excel file in Ajax?

Downloading Excel File using AJAX in jQuery Inside 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 do I save a file in Ajax?

Click the save button on the menu bar. A "Save As" box is open. Enter a name for your document. In this article, the name of the file is "index."


4 Answers

I looked for ways to pass JSON data with ajax to PHP and return an excel file (MySQL and PHPExcel) for the user to save. I looked around and put some pieces together, hope it can help someone:

jQuery:

$("#exportBotton").on("click",function(event) {
event.preventDefault();
// create json object;
str_json = JSON.stringify({"key01":val01, "key02":val02, "key03":val03});
        $.ajax({
              type: "post",
              data: str_json,
              url: "../../includes/dbSelect_agentFormExport.php",
              dataType: "json",
              success: function(output){
                          // output returned value from PHP t
              document.location.href =(output.url);
            }
       });
});

PHP:

 $str_json = file_get_contents('php://input');
 $objPHPExcel = new PHPExcel();
 // here i populated objPHPExcel with mysql query result.....

 function saveExcelToLocalFile($objWriter){
    // make sure you have permission to write to directory
    $filePath = '../tmp/saved_File.xlsx';
    $objWriter->save($filePath);
    return $filePath;
}

 $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
 $response = array(
     'success' => true,
     'url' => saveExcelToLocalFile($objWriter)
 );
 echo json_encode($response);
 exit();
like image 50
maozx Avatar answered Oct 20 '22 18:10

maozx


Not everything should be done with AJAX. Sometimes plain old HTML is more suitable for a job. I guess your button has a tag? Why won't you do something like this

<a href="generate_excel.php" target="_blank">Export to Excel</a>

in your HTML? Note the target="_blank" part. It's there to make sure your page is not reloaded.

For input you can use construct

<form action="generate_excel.php" target="_blank"><input type="button">...whatever</form>
like image 32
David Jashi Avatar answered Oct 20 '22 17:10

David Jashi


I don't think you can download anything by ajax call. Instead of you can generate and save the excel in server (temporary) and show the download link to the user.

like image 32
Debajit Mukhopadhyay Avatar answered Oct 20 '22 17:10

Debajit Mukhopadhyay


Found a way to do this, although I'm not sure if this is an ideal approach.

I added a hidden iframe in the page. When the ajax call returns, it returns the url of the created data. I used javascript to redirect the iframe to that url which automatically triggers the download action.

like image 29
John Ng Avatar answered Oct 20 '22 16:10

John Ng