0

I am displaying a report to the client. I have made an ajax call that passes in a "delivery" variable, which is either "display" or "download".

Here is the ajax call:

$.ajax({
        type: 'POST',
        url: 'ajaxController.php',
        dataType: 'json',
        data: {
            e: "getReport",
            reportName: reportName,
            delivery: delivery
        },
        success: function (data) {
            if (delivery === 'display') {
                $("#reportDisplayTableHeader").html('');
                $("#reportDisplayTableBody").html('');
                Lifestyle.selectedReportRows = data;

                $.each(Lifestyle.selectedReportRows, function(key, row) {
                    rowHTML = '<tr>';

                    $.each(row, function(parameter, value) {
                        if (isHeader) {
                            rowHTML += '<td>' + parameter + '</td>';
                        } else {
                            rowHTML += '<td>' + value + '</td>';
                        }
                    });

                    rowHTML += '</tr>';

                    if (isHeader) {
                        $reportHead.append(rowHTML);
                        isHeader = false;
                    } else {
                        $reportTableBody.append(rowHTML);
                    }
                });

                $("#reportCaption").show();
            }
        }
    });

And here is the server side PHP:

    if ($delivery == 'display') {
        echo json_encode($return);
    } else if ($delivery == 'download') {
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=file.csv");           
        header('Content-Description: File Transfer');
        header("Pragma: no-cache");
        header("Expires: 0");
        echo "record1,record2,record3\n";
    }

In the case of "display" it returns the json just fine and the client side displays a table.

In the case of "download", I want it to pop up a download dialog where it can save off the CSV that I echo'd to them.

But what is happening is that the call is completing and the headers / csv is crossing the wire (thanks Fiddler), but no download dialog is appearing and the client does not know that I pushed csv to them.

What do I need to do in order to get the download dialog to pop up?

Thanks.

Lurk21
  • 2,307
  • 12
  • 37
  • 55

1 Answers1

1

An Ajax call can not download something, or at least it is really hard. Better is to open a new window to the location of the php file (Then you should be using GET though) and then the user will be promted to download it.

Michiel Dral
  • 3,932
  • 1
  • 19
  • 21