Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
Can't download xlsx file in PHP through it's created

In public/js file, I request $ajax, and get responding just string, not file.

If the client sends a request using ajax, the server responds with a string instead of xlsx file.

Here is request part:

$("#downloadXLS").on('click', function () {
        $.ajax({
            type: 'get',
            url: appRoot + "transactions/downloadXLS/",

            success: function () {
            },

            error: function () {
            }
        });
    });

And here is php responding function:

public function downloadXLS()
  {
    // Filter the excel data 
    function filterData(&$str)
    {
      $str = preg_replace("/\t/", "\\t", $str);
      $str = preg_replace("/\r?\n/", "\\n", $str);
      if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
    }

    // Excel file name for download 
    $fileName = "transaction-data_" . date('Y-m-d') . ".xls";

    // Column names 
    $fields = array('No.',  'Pay Date',  'Company');

    // Display column names as first row 
    $excelData = implode("\t", array_values($fields)) . "\n";

    // Headers for download 
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=\"$fileName\"");

    $allTranscations = $this->transaction->getAll();
    if (is_array($allTranscations)) {
      // Output each row of the data 
      foreach ($allTranscations as $key => &$trans) {
        $lineData = array($key + 1, $trans->pay_time, $trans->company);
        array_walk($lineData, 'filterData');
        $excelData .= implode("\t", array_values($lineData)) . "\n";
      }
    } else {
      $excelData .= 'No records found...' . "\n";
    }

    // Render excel data 
    echo $excelData;

    exit();
  }

enter image description here

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can't download file via ajax request. Try location.href=transactions/downloadXLS.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda