2

Im trying to send data like string or even files to server via jquery ajax. Strings are appending to that FormData() but not files. I don't know why! Here is what I'm trying:

var dataFiles = new FormData();
dataFiles.append('file', $('#file-' + boardId)[0].files[0]);
dataFiles.append('boardId', boardId);
dataFiles.append('_token', $('meta[name="csrf-token"]').attr('content'));
dataFiles.append('message', encodeURIComponent(message));
$.ajax({
    method: "POST",
    type: "POST",
    url: url,
    data: dataFiles,
    cache: false,
    contentType: false,
    processData: false,
}).done(function (msg) {});

Edit: That file exist, I checked that too in console.log()

Mustapha Larhrouch
  • 3,373
  • 3
  • 14
  • 28
Gen Fa
  • 55
  • 1
  • 7
  • Possible duplicate of [How to append multiple file inputs to a FormData object using $.each?](https://stackoverflow.com/questions/21901528/how-to-append-multiple-file-inputs-to-a-formdata-object-using-each) – hs-dev2 MR Jul 11 '19 at 07:42
  • The code you've got should work. Check that the data you're adding to `file` by doing `console.log($('#file-' + boardId)[0].files[0].size)` – Rory McCrossan Jul 11 '19 at 07:43
  • @RoryMcCrossan I know but this problem is only with files, idk. However I did that and it has size , like 12805. The file is there – Gen Fa Jul 11 '19 at 07:46
  • In which case it sounds like the JS is sending data correctly, but your server side logic is not handling it correctly. – Rory McCrossan Jul 11 '19 at 07:48
  • Im getting response correctly for those others variables like boardId, message or even _token, file is empty in response ( file{}) – Gen Fa Jul 11 '19 at 07:50
  • Exactly. What is your server side logic and how are you receiving that file data? – Rory McCrossan Jul 11 '19 at 07:50
  • Take a look https://stackoverflow.com/questions/37672531/post-is-not-working-in-ajax-form-submit – hs-dev2 MR Jul 11 '19 at 07:53
  • Im actually just trying to get all request from that ajax post and storing in db. Is that what are you asking? Im using laravel and there is syntax $request->all(), to get all requests – Gen Fa Jul 11 '19 at 07:55
  • I got it . It is your server side problem . You can't retrieve file by $request->all() , you should do by $request->file('file'); – hs-dev2 MR Jul 11 '19 at 07:58
  • Yeah thats it. Thank you all – Gen Fa Jul 11 '19 at 08:02

0 Answers0