Rummaan
Rummaan

Reputation: 41

How to send ajax response like download button to download files Laravel

I want to display download link button on my view (if my ajax is success) follwings is my download code to send ajax response and dispaly on view

<div class="blog-moder-button">
  <a  href="public_path('files').'/'.$request->file_name" class="button-md dark-button downlds">
    Download PDF
  </a>
</div>

following is my controller

public function 

downloadform(Request $request) {        
  $validator = Validator::make($request->all(),[
    'name' => 'required',
    'email' => 'required|email',
    'file_name' => 'required',
     ]
  );

  if ($validator->passes()) {
    $msg= array();
    // $msg['success'] = '<div class="alert alert-success"> Successfully Registered</div>';//it is working 
    $msg['success'] = '<div class="blog-moder-button"> <a  href="public_path('files').'/'.$request->file_name"  class="button-md dark-button downlds"> Download PDF</a></div>';//it is not working
  }

  return response()->json($msg);
}

Upvotes: 0

Views: 1980

Answers (1)

Christophvh
Christophvh

Reputation: 13244

Do not render html inside your controller, that is the job of your view.

To trigger a file download response use this:

return response()->download($pathToFile);

https://laravel.com/docs/5.6/responses#file-downloads

Upvotes: 1

Related Questions