1

Im trying to send file to api using ajax , but form-data always null in both cases mentioned below

<form id="myformdoc">
    <input type="file" size="45" name="file" id="file">
</form>

           <script>
          $('#file').on("change", function () {
        
          // var formdata = new FormData($('form').get(0));
          
          let myForm = document.getElementById('myformdoc');
          let formData = new FormData(myForm);

    
        $.ajax({
            url: url,
            type: 'POST',
            data: formdata ,
            cache: false,
            processData: false,
            contentType: false,
            success: function (color) {
                ;
            },
            error: function () {
                alert('Error occured');
            }
        });
    
});
</script>

Any idea why form-data always null ?

3
  • in form tag add enctype="multipart/form-data" Commented Aug 13, 2020 at 10:49
  • Ahmed Sunny , i tried but same problem , formdata always empty {} Commented Aug 13, 2020 at 10:55
  • you are trying to get a form by id = myformdoc , but your form dont have that id Commented Aug 13, 2020 at 10:58

2 Answers 2

2

Try adding multipart/form-data in contentType parameter.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use formData append to add files to your formData function.

Change your jQuery code to this below and it will work fine and you can get the files on your backend to save them.

If you have other inputs in your form you can append them as well if you like to.

formData.append('file', $(this)[0].files[0])

Demo:

$('#file').on("change", function() {
  //Initialize formData
  let formData = new FormData();
  console.log($(this)[0].files)
  formData.append('file', $(this)[0].files[0]) //append files to file formData

  $.ajax({
    url: 'url',
    type: 'POST',
    data: formData,
    cache: false,
    processData: false,
    contentType: false,
    success: function(color) {
      console.log(color);
    },
    error: function() {
      alert('Error occured');
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data">
    <input type="file" size="45" name="file" id="file">
</form>

1 Comment

Worth mentioning that new FormData('id_of_the_form') will implicitly add all the form fields in the <form id="id_of_the_form" enctype="multipart/form-data">

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.