skip to Main Content

This is my ajax request:

var files = $('#imgur_attach')[0].files;

  if(files.length > 0){
    var fd = new FormData();
    
    // Append data 
    fd.append('file',files[0]);
    fd.append('_token',$globalToken);

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: false,
        processData: false,
        url: host + "/attach-comment-image/" ,
        data: {fd},

Controller:

public function attach(Request $request) {
    
    $this->validate($request, [
        'file' => 'image|required',
    ]);     
    

When sending this ajax request, the validator tells me that the "file" field is required. Trying to return request->get('file') returns null.

However, when I do console.log(fd); before the ajax request, it returns the following:
enter image description here

Why is this happening? I don’t normally upload files with AJAX over a regular POST request, so I don’t understand what I’m missing.

3

Answers


  1. Chosen as BEST ANSWER

    Wrapping the input around with a form tag like this did the trick:

    <form method="POST" enctype="multipart/form-data">
    

    Not sure why setting contentType: "multipart/form-data" in the ajax request doesn't work, but this solution works so I'll just use this instead.


  2. Try stringify data before sending like this:

    $.ajax({
      ...
      data: {fd: JSON.stringify(fd),
      ...
    
    Login or Signup to reply.
  3. you need to add multipart form data

    contentType: "multipart/form-data",
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search