I’m creating an application that will allow a user to fill out a form and then have a customized zip file downloaded for them upon submit. I’m utilizing AJAX to accomplish this task.
Build.prototype.ajaxHandler = function(method, values) {
jQuery.ajax({
type: 'POST',
url: WP_LOCALIZED['url'],
data: {
action: 'request_handler',
method: method,
data: values
}, success: function(data) {
var response = jQuery.parseJSON(data);
console.log(response);
}, error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest, textStatus, errorThrown);
}
});
};
Whenever I try to return basic data with my ajax handler I am able to successfully return without issue, but when I try to process my zip file method I consistently get Uncaught SyntaxError: Unexpected token <
even though the zip_file()
method is not actually returning any data back to the javascript method.
/**
* AJAX handler
*
* @return {json}
* @since 1.0
*/
public function request_handler()
{
$post = $_POST;
$data = $post['data'];
// If this wasn't here it would return my $data variable
$this->zip_file();
die(json_encode($data));
}
I’ve also tested the zip_file()
method on its own by placing it in the init()
function and it runs just as I would expect it to without issue.
/**
* Create Zip File
*
* @return void
* @since 1.0
*/
public function zip_file()
{
$zip = new ZipArchive;
if($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
if($zip->addEmptyDir($this->_plugin_path . 'assets/temp_files')) {
// Do stuff
}
$zip->close();
}
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=filename.zip');
header('Content-Length: ' . filesize($zip));
readfile($zip);
}
Interestingly the same thing happens if I replace the $this->zip_file()
call with just a basic echo
statement. Except instead of telling me the Unexpected token
is <
it says e
instead.
I think I’m misunderstanding something fundamental about the way these two interact together, but so far have not been able to locate any information on what that may be.
Any help would be appreciated.
Try to clear the buffer before returning your AJAX response.