2

In this code I want to specify the filename when downloading the excel format.

if(comp_id != "Select Company")
{
  $.ajax({
    url: 'includes/export.php',
    data: {
      action: 'compreport', 
      'comp':comp_id,   
    },
    type: 'post',
    success: function (output) {
      $("#ereportview").html(output);
      window.open('data:application/vnd.ms-excel,' + encodeURIComponent( $('div[id$=ereportview]').html()));
      e.preventDefault();
    },
    async: false
  });  
}
Neha Choudhary
  • 4,840
  • 2
  • 16
  • 22
Kalaivani M
  • 1,250
  • 15
  • 29

1 Answers1

1

use this download function in your success callback

function download(filename, text, mime) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:'+mime+',' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

you can use it like this:

if(comp_id != "Select Company") {
  $.ajax({
    url: 'includes/export.php',
    data: {
      action: 'compreport', 
      'comp':comp_id,   
    },
    type: 'post',
    success: function (output) {
      download("yourfile.xlsx", output, 'application/vnd.ms-excel');
    },
    async: false
  });  
}

you can specify MIME for the type of content you're downloading. You can get that from SitePoint

Community
  • 1
  • 1
NaN
  • 485
  • 3
  • 12