V
V
vista1x2015-03-10 10:24:40
PHP
vista1x, 2015-03-10 10:24:40

Give a file from PHP?

Hello!
I will describe the situation: there is a PHP script that generates a zip archive and sends it to the browser for download. In the process of creating an archive, errors may occur, in which case json data about this error is returned. The script itself is called from JS.
Now in JS it is implemented like this:
location.href='/scr.php';
If there are no errors, the file is normally downloaded by the browser. If there are errors, it goes to scr.php, which displays the text in JSON format.
Question: how to handle this error in JS and act depending on the situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Goryachkin, 2015-03-10
@vista1x

Make an ajax request. If everything is fine, then return a link to the created zip archive and jump to it, or create an a tag and emulate a click on it:

var link = document.createElement("a");
link.href = "test";
link.download = "test.zip";
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);

Well, if there are errors, then here you can process as your heart desires.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question