-2

Im writing an application which have to make export json files filled with data.
I dont have the code on this machine to show you, so I'm going to cut to the chase.
I have a HTML table and a button.
Clicking on the button is handled by jQuery function which collects the needed data from the form and puts it in array.

The next thing which is happening is an AJAX POST request.
The post sends the array to a PHP method which generates the json file.
I don't want to save the file to the server, so I manualy set the headers to force download the generated file. Which means that I dont have any physical link to the file.
The problem is that I don't get any download dialog. I think that jquery ajax function prevents it.
How can I get the download dialog?

Okay here is some code...

PHP

public function GetFile() {
    foreach ($this->input->post("data") as $data) {
        $linesData = explode("@", $data);
        $modelsata = explode("@", $linesData[1]);
        $modData = explode("#", $data);
        $lines[$linesData[0]] = array(
            "model" => $modelsData[0], "mod" => $modData[1]
        );
    }
    force_download("export.json", json_encode($lines));
}

JS

$("button.export").click(function () {
    var dataArr = [];
    $.each($("tr.data"), function (index, element) {
        dataArr.push($(element).data("rowid")
            + "@" + $(element).find("select[name='model']").val()
            + "#" + $(element).find("select[name='mod']").val()
        );
    });
    $.post("http://localhost/index.php/AJAX/GetFile", {data: dataArr});
});
Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
Alex Shun
  • 11
  • 1

1 Answers1

0

You need to set the headers:

public function download_json()
{

    $a = array(
        'test1' => 1,
        'test2' => 2,
        'test3' => 3
    );

    $data = json_encode($a);
    $filename = 'testjson';
    header('Content-Type: application/json');
    header('Content-Disposition: attachment; filename=' . $filename);
    echo $data;


}

The user guide isn't really clear on what exactly force_download() does in terms of headers, but this should work.

stormdrain
  • 7,915
  • 4
  • 37
  • 76