I have a button in my WordPress
page. when user clicks it, I make an Ajax
request to functions.php
and it should create a file and send it to user as a downloaded file.
here are the parts of codes:
userProfile.php:
<?php
echo "<input id='getUsersButton' type='button' class='actionButton' value='Download Users Email'/>";
?>
<script>
jQuery(document).ready(function ($) {
$('#getUsersButton').on('click', function (e) {
e.preventDefault();
var ajax_url = ajax_params.ajax_url;
var data = {
'action': 'them_getUsersEmail',
};
$.post(ajax_url, data, function (response) {
if (JSON.parse(response) == true) {
window.alert("Sending your request...");
} else {
window.alert("Error Handling Request");
}
});
});
});
</script>
functions.php:
<?php
function them_getUsersEmail() {
$file = "test.txt";
$txt = fopen($file, "w") or die("Unable to open file!");
fwrite($txt, "test data");
fclose($txt);
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: text/plain");
header("Content-Type: application/download");
ob_clean();
flush();
readfile($file);
echo json_encode(true);
exit();
}
add_action('wp_ajax_them_getUsersEmail', 'them_getUsersEmail');
add_action('wp_ajax_nopriv_them_getUsersEmail', 'them_getUsersEmail');
?>
my problem is that I expect to receive a file after executing of them_getUsersEmail
but instead, I will receive test.txt
content(test data
) as response variable in ajax
callback in userProfile.php
.
I also changed Ajax
request as bellow but nothing changed and no file will be downloaded:
$.post(ajax_url, data);
I am new to php
so my question is that if I am using the correct approach for implementation and if I am correct, how can I fix the problem?
thank you.
P.S: I would like to inform user that his request is accepted or rejected so I considered related window.alert
s.