Download excel file with ajax call

16,623

Solution 1

I solved my issue by following way.

add target=_blank in your ajax success function like below

success: function(){
  window.open('http://MY_URL','_blank' );
},

On success open new window with my_url.

Solution 2

PHP

$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
ob_start();
$objWriter->save("php://output");
$xlsData = ob_get_contents();
ob_end_clean();

$response =  array(
        'op' => 'ok',
        'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
    );

die(json_encode($response));

JS

$.ajax({
    type:'POST',
    url:"MY_URL.php",
    data: {},
    dataType:'json'
}).done(function(data){
    var $a = $("<a>");
    $a.attr("href",data.file);
    $("body").append($a);
    $a.attr("download","file.xls");
    $a[0].click();
    $a.remove();
});
Share:
16,623
Sadikhasan
Author by

Sadikhasan

I am web service/API &amp; Web developer having great knowledge and experience of developing and designing webservice for android and iPhone. I am working on Senior Node JS Developer. BackeEnd : MySQL and Neo4J and MongoDB Senior Node JS Developer at AIS Technolabs Pvt Ltd, Ahmedabad.

Updated on June 04, 2022

Comments

  • Sadikhasan
    Sadikhasan almost 2 years
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getActiveSheet()->setTitle('TestMessages');
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment; filename=test_form_".date("Y-m-d_H:i:s").".xls");
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    

    When I call above code directly from the browser, the result file is downloaded. But if I make an ajax call to above code, I don't get the download prompt. I can see from console 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.

    I reffer Passing data from PHP class to PHPExcel via AJAX but do not understand how to achieve my goal?