0

I need to download CSV file inside ajax call.

I can access my ajax request in Laravel controller. And I can get the response of file contents as well in the success function of my ajax call. But the file is not being downloaded.

laravel controller code :

public function export($request) { $details = $this->myService->getData($request); $csv_data = new Collection(); if ($details->count() === 0) { return $csv_data; } foreach ($details as $detail) { $collection = collect([ 'id' => $detail->id, ]); $csv_data->push($collection); } $csv_file_name = abc.csv; $csv_headers = 'id']; $csv_column_names = [ 'id']; $callback = function () use ($csv_data, $csv_file_name, $csv_headers, $csv_column_names) { $stream = fopen('php://output', 'w'); stream_filter_prepend($stream, 'convert.iconv.utf-8/cp932//TRANSLIT'); $header = '"'; $header .= implode('","', $csv_headers); $header .= '"'; $header .= "\r\n"; fwrite($stream, $header); foreach ($csv_data as $row) { $arr_data = []; foreach ($csv_column_names as $column_name) { array_push($arr_data, $row->get($column_name)); } $data = '"'; $data .= implode('","', $arr_data); $data .= '"'; $data .= "\r\n"; fwrite($stream, $data); } fclose($stream); }; $filename = $csv_file_name; $header = [ 'Content-Type' => 'application/octet-stream', ]; return response()->streamDownload($callback, $filename, $header); } 

My ajax call

$('#csv-file').on('click',function(e){ e.preventDefault(); let id = $("select[name='user_id']").val(); $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: "/user/csv", type:"POST", data:{ id:id, }, success:function(response){ $( "#error" ).remove(); console.log(response); }, error: function(response) { $( "#error" ).remove(); let errorView = `<div class="alert alert-error" id="error"> <h6>Error:</h6> <ul class="flex flex-col items-start"> <li>`+ response.responseJSON.message + `</li> </ul> </div>`; $("#error-id").prepend(errorView); }, }); }); 

Inside the success function of my ajax call, I can console log and get the file contents. But I need to download the file which is not being downloaded.

Thanks in advance.

0

1 Answer 1

1

add this to your ajax params:

xhrFields: { responseType: "blob", } 

now, inside the success function, add:

let a = document.createElement("a") a.href = URL.createObjectURL(response) a.download = response.filename a.style.display = "none" document.body.appendChild(a) a.click() 

this should work.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.