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.