stack stack - 1 month ago 8
PHP Question

Why my ajax request always throws error?

Here is my code:

PHP:

public function export(Request $request){

$file = "export.txt";
if(isset($_POST["type"])){
file_put_contents("$file",$_POST["text"]);
}
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: text/plain'); // the appropriate header type for txt file
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
}


JS:

$(document).on('click', '#export', function () {
var names = ['علی','فرید'];
var namess = names.join('\n');
$.ajax({
type: "post",
url: "/export",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
type: "save",
text: namess
},
dataType: "json",
success: function(){
var href = '/export?filename=export.txt';
window.location = href;
},
error: function(){
alert('wrong');
}
});
})


Always
error
part executes. I mean it always alert
wrong
. How can I fix it? All I'm trying to do it making a
.txt
download file.

Noted that when I run this path:
http://localhost:8000/export?filename=export.txt
.. then
export.txt
will be downloaded.

Answer

You can download using this code:

window.location="export?filename=export.txt";

If you want to post data :

   $('<form action="comments.php" method="POST"/>')
        .append($('<input type="hidden" name="type" value="save">'))
       .append($('<input type="hidden" name="text" value="'+ namess +'">'))
        .appendTo($(document.body)) //it has to be added somewhere into the <body>
        .submit();

Full code:

 $(document).on('click', '#export', function () {

    var names =  ['علی','فرید'];
    var namess = names.join('\n');

     $('<form action="export?filename=export.txt" method="POST"/>')
        .append($('<input type="hidden" name="type" value="save">'))
       .append($('<input type="hidden" name="text" value="'+ namess +'">'))
        .appendTo($(document.body)) //it has to be added somewhere into the <body>
        .submit();

    });

});