Prompt user to save file through AJAX call

喜你入骨 提交于 2019-11-30 14:00:17

You can't prompt the user to download a file from an AJAX call. One thing you can do is, make an iFrame, put a form in it, then POST it. That way, it'll look like an AJAX call, but the user will be prompted to download the file.

// Create iFrame
var iframe = document.createElement('iframe');
iframe.style.display = "none";
document.body.appendChild(iframe);

// Get the iframe's document
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

// Make a form
var form = document.createElement('form');
form.action = 'data/export.php'; // Your URL
form.method = 'POST';

// Add form element, to post your value
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'csvdata';
input.value = gridCsvData;  // Your POST data

// Add input to form
form.appendChild(input);

// Add form to iFrame
// IE doesn't have the "body" property
(iframeDoc.body || iframeDoc).appendChild(form);

// Post the form :-)
form.submit();

P.S. Your PHP code doesn't actually echo the CSV to the screen, it just saves it to a file.

After the header calls, make sure you have:

readfile($myfile);

The right way to do this in HTML5 is to use the File API. See this for details: http://hackworthy.blogspot.com/2012/05/savedownload-data-generated-in.html.

If HTML5 is not an option, then take this approach.

After you do a POST, generate a GET request for the file using:

document.location = "file.csv";

Depending on the browser, the file will either be saved (Chrome) or user will be prompted to choose a file name to save as. Of course, the POST handler has to save the file somewhere.

$.ajax({
    type: "POST",
    url: "post.php",
    success: function() {
        console.log("Worked!");
        document.location = "test.csv";
    },
    error: function() {
        console.log("Failed!");
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!