1

In my code, I am not using the form tag to submit the form data to the server. Instead i am trying to identify the fields with the id and send it using JQuery. My code is as follows:

I need to pass enctype as multipart/form-data. How can I do so from JQuery ?

The following code is done using the form tag. It works. But, I need to send the request via JQuery. How am I supposed to do this ?

USING FORM tag

 <form action="/" method="post" enctype="multipart/form-data" >
      <input  name="fileis"  type="file" ></br>
      <input type="submit" value="submit" />

</form>

What I want is to send a request to / without using the form tag. My code is as follows:

HTML

<input  type="file" name="fileis" id="uploadinput" ></br>

JQUERY - How to pass the enctype ?

$('#uploadinput').on('change', function(){

  var files = $(this).get(0).files;

  if (files.length > 0){
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();



    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      formData.append('uploads[]', file, file.name);

    }

    $.ajax({
      url: '/',
      type: 'post',
      data: formData,
      processData: false,
      contentType: false,
      cache: false,


      success: function(data){
          console.log('upload successful!\n' + data);
      },
      xhr: function() {
        // create an XMLHttpRequest
        var xhr = new XMLHttpRequest();

        // listen to the 'progress' event
        xhr.upload.addEventListener('progress', function(evt) {

          if (evt.lengthComputable) {
            // calculate the percentage of upload completed
            var percentComplete = evt.loaded / evt.total;
            percentComplete = parseInt(percentComplete * 100);

            // update the Bootstrap progress bar with the new percentage
            $('.progress-bar').text(percentComplete + '%');
            $('.progress-bar').width(percentComplete + '%');

            // once the upload reaches 100%, set the progress bar text to done
            if (percentComplete === 100) {
              $('.progress-bar').html('Done');
            }

          }

        }, false);

        return xhr;
      }
    });

  }
});
Illep
  • 16,375
  • 46
  • 171
  • 302
  • You've already set `contentType: false` - so that will take care of it for you. Have you tried your code? It should work fine as it is. Do you have a specific issue with it? – Rory McCrossan Jul 30 '16 at 20:00
  • it hasn't. How can I pass `enctype` anyway. – Illep Jul 30 '16 at 20:01

0 Answers0