I have a perl script URL which gives me a ZIP file, it processes the data and dynamically set the Content-Type to 'application/zip' in the http-header.
Perl code looks like this:
WPHTTPResponse::setHeader( 'Content-disposition', 'attachment;filename="test.zip"');
WPHTTPResponse::setHeader( 'Content-type', 'application/zip');
print $result;
In frontend, I am using this script direct in HREF:
<a href="/script">Download</a>
But I have a requirement of showing an alert message if $result is NULL in perl script.
What I am thinking is: I will send the file with Content-Type=>application/zip if the $result if not null, otherwise I will send the JSON response with error message that there is no file to download.
For this I would need to dynamically check the content type using JS:
$.ajax({
url: '/script',
data: {....},
success: function(response) {
if(response.contentType == 'application/zip'){
//download using javascript
}
else{
$.parseJSON(response);
alert(response.msg);
}
}
});
I’d appreciate any help.
Although your method should work, this is a case where using using HTTP error codes would probably be a good choice.
Depending on why $result is null one of these should be appropriate.
This would make your code slightly more ‘obvious’ as you would be using the HTTP status for exactly what it was meant for, rather than re-implementing the exact same thing in a proprietary way in your code. IMHO it would also make your code a bit easier to maintain as it would separate the success from the error.
You can still include JSON as part of the error response, to be able display information about exactly why the request didn’t result in any data being returned to the client.
btw I’d avoid using 404 as the error code, even though it is technically the most ‘appropriate’ code just because it would cause confusion if a real 404 error occurred.