Listen for Cookie Change
I recently hacked around an interesting problem that involved executing some jQuery after setting several ZIP file download HTTP header fields. My initial thought was to make use of an AJAX post request to set the requisite headers and use the relevant deferred methods to take action on the response. Unfortunately, given the circumstances, this didn’t appear to be a viable option.
Download Complete?
I wanted to take some action (display a success message, in this case) after the download had been “forced.” And, for whatever reason, setting the headers seemed to disorient the script. (I say “disorient,” rather than “halt,” because commands after the header()
declarations did execute.) In any case, I needed a different solution.
...
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
...
Eventually, this thought crossed my mind: If I can’t return data from this function (in which the headers are set), I’ll need some other way to communicate the appropriate message to the browser. Then, it occurred to me that this could be a job for cookies.
How the Cookie Crumbles
First, I would set a cookie on the initial page load.
...
setcookie('message', 'none');
...
Then, just before setting the headers in my ZIP download script, I would alter the cookie.
...
setcookie('message', $success_message);
header("Content-type: application/octet-stream");
...
Not complicated, I know. My form post would now take care of the ZIP download forcing and cookie value changing. But where did that get me?
Listen for Cookie Change
Since I wasn’t forcing the browser to reload the page (due to the placement of the new header commands and (probably) a lack of the right knowledge), I would need to actively “listen” for this cookie change in order to trigger the appropriate jQuery. Luckily, someone pieced together a neat little JSFiddle for the occasion. This made things simple.
listenCookieChange('message', function() {
...
addMessage();
...
});
With a little effort, I had a solution that worked. It felt good.
–
As I mentioned, I’m sure there exists a much more elegant solution here. Thinking about these struggles (as I’ve unzipped them) has made this clearer. You live and you learn, I suppose.