0

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.

7
  • 1
    what's is in AJAX's payload? Commented Dec 31, 2022 at 4:52
  • In the console.log(fd) you already see, that file -> {}, so it isn't filled. In your fd.append('file',files[0]);, see if you get something from files[0], this is purely debugging. What is in var files, for example? Commented Dec 31, 2022 at 4:58
  • @UnderDog console.log(files); returns the following: FileList [ File ] ​ 0: File { name: "Untitled.png", lastModified: 1672461379071, size: 17639, … } ​ length: 1 Commented Dec 31, 2022 at 5:13
  • @AliRaza how can I show you the payload? Commented Dec 31, 2022 at 5:23
  • 1
    Using the network tab in dev tools for your browser: e.g: stackoverflow.com/questions/15603561/… Commented Dec 31, 2022 at 5:29

3 Answers 3

1

Try stringify data before sending like this:

$.ajax({
  ...
  data: {fd: JSON.stringify(fd),
  ...
Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't work. Request payload is still just [object Object]. I also tried removing processData: false, since you're stringifying but that didn't work either.
1

you need to add multipart form data

contentType: "multipart/form-data",

1 Comment

Doesn't do anything.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.