skip to Main Content

I tried to send a file using an Ajax POST request using two methods:

Method 1 (jQuery val())

$.ajax({
    url: 'somewhere',
    method: 'post',
    processData: true,
    contentType: true,

    data:{
      'data1': $('#fileinputid').val(),  // File input
}

success:function(){
    // Do something;
}

error:function(){
    // Do something;
},

});

Method 2- (FormData)

var formData = new FormData(document.getElementById("form-id"));

$.ajax({
    url: 'somewhere',
    method:'post',
    cache: false,
    processData:false,
    contentType: false,

    data: formData,

    success: function(){
        // Do something for success
    },

    error: function(){
        // Do something for error
    },

});

Now, Method 2 worked, but Method 1 did not. What is the reason for that?

2

Answers


  1. data1: formData you have a typo here.

    It should correctly be data: formData

    Login or Signup to reply.
  2. $('#fileinputid').val() only gets you the file name. You can not upload a file with that.

    FormData is capable of creating the whole multipart/formdata request structure that is needed for a file upload.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search