Home » Php » javascript – How to upload file using Ajax In Laravel I am getting error 419 (unknown status)

javascript – How to upload file using Ajax In Laravel I am getting error 419 (unknown status)

Posted by: admin February 25, 2020 Leave a comment

Questions:

How to upload file using Ajax In Laravel I am getting error 419 (unknown status).
1.Javascript Code.
2.Controller Code.
3.Router Code.

Javascript Code

$("#front_image").change(function() {
  let photo = document.getElementById("front_image").files[0];
  let formData = new FormData();
  formData.append("photo", photo);
  formData.append("names",'ABC');

  $.ajax({
      type: "POST",
      url:'/up',
      data:{"_token": $('meta[name="csrf-token"]').attr('content'),"formdata":formData},
      cache:false,
      contentType: false,
      processData: false,
      success:function(data){
          console.log("success");
         console.log(data);
      },
      error: function(data){
          console.log("error");
          console.log(data);
      }
  });
});

Controller Code

public function Image(Request $request) {
  return $request->get('names');
}

Router Code

Route::POST('/up', '[email protected]')
How to&Answers:

Try to add the CSRF-Token to your header like this:

$("#front_image").change(function() {
  let photo = document.getElementById("front_image").files[0];
  let formData = new FormData();
  formData.append("photo", photo);
  formData.append("names",'ABC');

  $.ajax({
    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
    type: "POST",
    url: '/up',
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
      console.log("success");
      console.log(data);
    },
    error: function(data){
      console.log("error");
      console.log(data);
    }
  });
});

Furthermore i would prefer to add the formData like this example above. So you can access it the way you did in your controller.