How to use FormData for ajax file upload












160















This is my html which I'm generating dynamically using drag and drop functionality.



<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>

<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>

<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">

<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>


this is my js code...



<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);

$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}









share|improve this question




















  • 1





    You should read this (developer.mozilla.org/en-US/docs/Web/API/FormData/append) the formData(); append method has an optional third parameter for a file.

    – www139
    Dec 26 '15 at 14:36
















160















This is my html which I'm generating dynamically using drag and drop functionality.



<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>

<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>

<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">

<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>


this is my js code...



<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);

$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}









share|improve this question




















  • 1





    You should read this (developer.mozilla.org/en-US/docs/Web/API/FormData/append) the formData(); append method has an optional third parameter for a file.

    – www139
    Dec 26 '15 at 14:36














160












160








160


90






This is my html which I'm generating dynamically using drag and drop functionality.



<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>

<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>

<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">

<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>


this is my js code...



<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);

$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}









share|improve this question
















This is my html which I'm generating dynamically using drag and drop functionality.



<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>

<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>

<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">

<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>


this is my js code...



<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);

$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}






php jquery ajax






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 18 '18 at 18:42









John

5,512750110




5,512750110










asked Jan 10 '14 at 12:47









KalpitKalpit

2,45921941




2,45921941








  • 1





    You should read this (developer.mozilla.org/en-US/docs/Web/API/FormData/append) the formData(); append method has an optional third parameter for a file.

    – www139
    Dec 26 '15 at 14:36














  • 1





    You should read this (developer.mozilla.org/en-US/docs/Web/API/FormData/append) the formData(); append method has an optional third parameter for a file.

    – www139
    Dec 26 '15 at 14:36








1




1





You should read this (developer.mozilla.org/en-US/docs/Web/API/FormData/append) the formData(); append method has an optional third parameter for a file.

– www139
Dec 26 '15 at 14:36





You should read this (developer.mozilla.org/en-US/docs/Web/API/FormData/append) the formData(); append method has an optional third parameter for a file.

– www139
Dec 26 '15 at 14:36












6 Answers
6






active

oldest

votes


















339














For correct form data usage you need to do 2 steps.



Preparations



You can give your whole form to FormData() for processing



var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);


or specify exact data for FormData()



var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);


Sending form



Ajax request with jquery will looks like this:



$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});


After this it will send ajax request like you submit regular form with enctype="multipart/form-data"



Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.



Note: contentType: false only available from jQuery 1.6 onwards






share|improve this answer





















  • 1





    Can I set the "enctype" in the Ajax call? I think I may have an issue with it. Or, can I set it on the FormData object?

    – Wouter
    Jun 1 '14 at 7:50











  • You can. For this see lines after THIS MUST BE DONE FOR FILE UPLOADING in my code.

    – Spell
    Jun 2 '14 at 12:37






  • 5





    How to collect the data in server side...

    – Rahul Matte
    Apr 28 '16 at 10:43











  • @Spell How get data in controller? Do need send getCsrfToken?

    –  Юрий Светлов
    May 22 '16 at 16:11






  • 1





    @ManthanJamdagni When you get $('form'), it will return jQuery object. But we need regular js object here without jQuery functionality. That's why we get regular object with [0] notation. Instead of this construction you can call document.getElementById() or simular call.

    – Spell
    Oct 22 '18 at 8:31



















28














I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add



type: "POST"



to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:



Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.



  $.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})





share|improve this answer

































    15














    <form id="upload_form" enctype="multipart/form-data">


    jQuery with CodeIgniter file upload:



    var formData = new FormData($('#upload_form')[0]);

    formData.append('tax_file', $('input[type=file]')[0].files[0]);

    $.ajax({
    type: "POST",
    url: base_url + "member/upload/",
    data: formData,
    //use contentType, processData for sure.
    contentType: false,
    processData: false,
    beforeSend: function() {
    $('.modal .ajax_data').prepend('<img src="' +
    base_url +
    '"asset/images/ajax-loader.gif" />');
    //$(".modal .ajax_data").html("<pre>Hold on...</pre>");
    $(".modal").modal("show");
    },
    success: function(msg) {
    $(".modal .ajax_data").html("<pre>" + msg +
    "</pre>");
    $('#close').hide();
    },
    error: function() {
    $(".modal .ajax_data").html(
    "<pre>Sorry! Couldn't process your request.</pre>"
    ); //
    $('#done').hide();
    }
    });


    you can use.



    var form = $('form')[0]; 
    var formData = new FormData(form);
    formData.append('tax_file', $('input[type=file]')[0].files[0]);


    or



    var formData = new FormData($('#upload_form')[0]);
    formData.append('tax_file', $('input[type=file]')[0].files[0]);


    Both will work.






    share|improve this answer

































      1














      $('#form-withdraw').submit(function(event) {

      //prevent the form from submitting by default
      event.preventDefault();



      var formData = new FormData($(this)[0]);

      $.ajax({
      url: 'function/ajax/topup.php',
      type: 'POST',
      data: formData,
      async: false,
      cache: false,
      contentType: false,
      processData: false,
      success: function (returndata) {
      if(returndata == 'success')
      {
      swal({
      title: "Great",
      text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
      type: "success",
      showCancelButton: false,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "OK",
      closeOnConfirm: false
      },
      function(){
      window.location.href = '/transaction.php';
      });
      }

      else if(returndata == 'Offline')
      {
      sweetAlert("Offline", "Please use other payment method", "error");
      }
      }
      });



      });





      share|improve this answer































        1














        Actually The documentation shows that you can use XMLHttpRequest().send()
        to simply send multiform data
        in case jquery sucks






        share|improve this answer

































          0














          View:
          <label class="btn btn-info btn-file">
          Import <input type="file" style="display: none;">
          </label>
          <Script>
          $(document).ready(function () {
          $(document).on('change', ':file', function () {
          var fileUpload = $(this).get(0);
          var files = fileUpload.files;
          var bid = 0;
          if (files.length != 0) {
          var data = new FormData();
          for (var i = 0; i < files.length ; i++) {
          data.append(files[i].name, files[i]);
          }
          $.ajax({
          xhr: function () {
          var xhr = $.ajaxSettings.xhr();
          xhr.upload.onprogress = function (e) {
          console.log(Math.floor(e.loaded / e.total * 100) + '%');
          };
          return xhr;
          },
          contentType: false,
          processData: false,
          type: 'POST',
          data: data,
          url: '/ControllerX/' + bid,
          success: function (response) {
          location.href = 'xxx/Index/';
          }
          });
          }
          });
          });
          </Script>
          Controller:
          [HttpPost]
          public ActionResult ControllerX(string id)
          {
          var files = Request.Form.Files;
          ...





          share|improve this answer



















          • 6





            It is normally considered good form to provide an explanation along with an answer.

            – ouflak
            Oct 27 '16 at 19:42











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f21044798%2fhow-to-use-formdata-for-ajax-file-upload%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          339














          For correct form data usage you need to do 2 steps.



          Preparations



          You can give your whole form to FormData() for processing



          var form = $('form')[0]; // You need to use standard javascript object here
          var formData = new FormData(form);


          or specify exact data for FormData()



          var formData = new FormData();
          formData.append('section', 'general');
          formData.append('action', 'previewImg');
          // Attach file
          formData.append('image', $('input[type=file]')[0].files[0]);


          Sending form



          Ajax request with jquery will looks like this:



          $.ajax({
          url: 'Your url here',
          data: formData,
          type: 'POST',
          contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
          processData: false, // NEEDED, DON'T OMIT THIS
          // ... Other options like success and etc
          });


          After this it will send ajax request like you submit regular form with enctype="multipart/form-data"



          Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.



          Note: contentType: false only available from jQuery 1.6 onwards






          share|improve this answer





















          • 1





            Can I set the "enctype" in the Ajax call? I think I may have an issue with it. Or, can I set it on the FormData object?

            – Wouter
            Jun 1 '14 at 7:50











          • You can. For this see lines after THIS MUST BE DONE FOR FILE UPLOADING in my code.

            – Spell
            Jun 2 '14 at 12:37






          • 5





            How to collect the data in server side...

            – Rahul Matte
            Apr 28 '16 at 10:43











          • @Spell How get data in controller? Do need send getCsrfToken?

            –  Юрий Светлов
            May 22 '16 at 16:11






          • 1





            @ManthanJamdagni When you get $('form'), it will return jQuery object. But we need regular js object here without jQuery functionality. That's why we get regular object with [0] notation. Instead of this construction you can call document.getElementById() or simular call.

            – Spell
            Oct 22 '18 at 8:31
















          339














          For correct form data usage you need to do 2 steps.



          Preparations



          You can give your whole form to FormData() for processing



          var form = $('form')[0]; // You need to use standard javascript object here
          var formData = new FormData(form);


          or specify exact data for FormData()



          var formData = new FormData();
          formData.append('section', 'general');
          formData.append('action', 'previewImg');
          // Attach file
          formData.append('image', $('input[type=file]')[0].files[0]);


          Sending form



          Ajax request with jquery will looks like this:



          $.ajax({
          url: 'Your url here',
          data: formData,
          type: 'POST',
          contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
          processData: false, // NEEDED, DON'T OMIT THIS
          // ... Other options like success and etc
          });


          After this it will send ajax request like you submit regular form with enctype="multipart/form-data"



          Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.



          Note: contentType: false only available from jQuery 1.6 onwards






          share|improve this answer





















          • 1





            Can I set the "enctype" in the Ajax call? I think I may have an issue with it. Or, can I set it on the FormData object?

            – Wouter
            Jun 1 '14 at 7:50











          • You can. For this see lines after THIS MUST BE DONE FOR FILE UPLOADING in my code.

            – Spell
            Jun 2 '14 at 12:37






          • 5





            How to collect the data in server side...

            – Rahul Matte
            Apr 28 '16 at 10:43











          • @Spell How get data in controller? Do need send getCsrfToken?

            –  Юрий Светлов
            May 22 '16 at 16:11






          • 1





            @ManthanJamdagni When you get $('form'), it will return jQuery object. But we need regular js object here without jQuery functionality. That's why we get regular object with [0] notation. Instead of this construction you can call document.getElementById() or simular call.

            – Spell
            Oct 22 '18 at 8:31














          339












          339








          339







          For correct form data usage you need to do 2 steps.



          Preparations



          You can give your whole form to FormData() for processing



          var form = $('form')[0]; // You need to use standard javascript object here
          var formData = new FormData(form);


          or specify exact data for FormData()



          var formData = new FormData();
          formData.append('section', 'general');
          formData.append('action', 'previewImg');
          // Attach file
          formData.append('image', $('input[type=file]')[0].files[0]);


          Sending form



          Ajax request with jquery will looks like this:



          $.ajax({
          url: 'Your url here',
          data: formData,
          type: 'POST',
          contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
          processData: false, // NEEDED, DON'T OMIT THIS
          // ... Other options like success and etc
          });


          After this it will send ajax request like you submit regular form with enctype="multipart/form-data"



          Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.



          Note: contentType: false only available from jQuery 1.6 onwards






          share|improve this answer















          For correct form data usage you need to do 2 steps.



          Preparations



          You can give your whole form to FormData() for processing



          var form = $('form')[0]; // You need to use standard javascript object here
          var formData = new FormData(form);


          or specify exact data for FormData()



          var formData = new FormData();
          formData.append('section', 'general');
          formData.append('action', 'previewImg');
          // Attach file
          formData.append('image', $('input[type=file]')[0].files[0]);


          Sending form



          Ajax request with jquery will looks like this:



          $.ajax({
          url: 'Your url here',
          data: formData,
          type: 'POST',
          contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
          processData: false, // NEEDED, DON'T OMIT THIS
          // ... Other options like success and etc
          });


          After this it will send ajax request like you submit regular form with enctype="multipart/form-data"



          Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.



          Note: contentType: false only available from jQuery 1.6 onwards







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 22 '18 at 16:26









          Community

          11




          11










          answered Jan 10 '14 at 13:00









          SpellSpell

          4,18611020




          4,18611020








          • 1





            Can I set the "enctype" in the Ajax call? I think I may have an issue with it. Or, can I set it on the FormData object?

            – Wouter
            Jun 1 '14 at 7:50











          • You can. For this see lines after THIS MUST BE DONE FOR FILE UPLOADING in my code.

            – Spell
            Jun 2 '14 at 12:37






          • 5





            How to collect the data in server side...

            – Rahul Matte
            Apr 28 '16 at 10:43











          • @Spell How get data in controller? Do need send getCsrfToken?

            –  Юрий Светлов
            May 22 '16 at 16:11






          • 1





            @ManthanJamdagni When you get $('form'), it will return jQuery object. But we need regular js object here without jQuery functionality. That's why we get regular object with [0] notation. Instead of this construction you can call document.getElementById() or simular call.

            – Spell
            Oct 22 '18 at 8:31














          • 1





            Can I set the "enctype" in the Ajax call? I think I may have an issue with it. Or, can I set it on the FormData object?

            – Wouter
            Jun 1 '14 at 7:50











          • You can. For this see lines after THIS MUST BE DONE FOR FILE UPLOADING in my code.

            – Spell
            Jun 2 '14 at 12:37






          • 5





            How to collect the data in server side...

            – Rahul Matte
            Apr 28 '16 at 10:43











          • @Spell How get data in controller? Do need send getCsrfToken?

            –  Юрий Светлов
            May 22 '16 at 16:11






          • 1





            @ManthanJamdagni When you get $('form'), it will return jQuery object. But we need regular js object here without jQuery functionality. That's why we get regular object with [0] notation. Instead of this construction you can call document.getElementById() or simular call.

            – Spell
            Oct 22 '18 at 8:31








          1




          1





          Can I set the "enctype" in the Ajax call? I think I may have an issue with it. Or, can I set it on the FormData object?

          – Wouter
          Jun 1 '14 at 7:50





          Can I set the "enctype" in the Ajax call? I think I may have an issue with it. Or, can I set it on the FormData object?

          – Wouter
          Jun 1 '14 at 7:50













          You can. For this see lines after THIS MUST BE DONE FOR FILE UPLOADING in my code.

          – Spell
          Jun 2 '14 at 12:37





          You can. For this see lines after THIS MUST BE DONE FOR FILE UPLOADING in my code.

          – Spell
          Jun 2 '14 at 12:37




          5




          5





          How to collect the data in server side...

          – Rahul Matte
          Apr 28 '16 at 10:43





          How to collect the data in server side...

          – Rahul Matte
          Apr 28 '16 at 10:43













          @Spell How get data in controller? Do need send getCsrfToken?

          –  Юрий Светлов
          May 22 '16 at 16:11





          @Spell How get data in controller? Do need send getCsrfToken?

          –  Юрий Светлов
          May 22 '16 at 16:11




          1




          1





          @ManthanJamdagni When you get $('form'), it will return jQuery object. But we need regular js object here without jQuery functionality. That's why we get regular object with [0] notation. Instead of this construction you can call document.getElementById() or simular call.

          – Spell
          Oct 22 '18 at 8:31





          @ManthanJamdagni When you get $('form'), it will return jQuery object. But we need regular js object here without jQuery functionality. That's why we get regular object with [0] notation. Instead of this construction you can call document.getElementById() or simular call.

          – Spell
          Oct 22 '18 at 8:31













          28














          I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add



          type: "POST"



          to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:



          Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.



            $.ajax({
          url: 'Your url here',
          data: formData,
          type: "POST", //ADDED THIS LINE
          // THIS MUST BE DONE FOR FILE UPLOADING
          contentType: false,
          processData: false,
          // ... Other options like success and etc
          })





          share|improve this answer






























            28














            I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add



            type: "POST"



            to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:



            Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.



              $.ajax({
            url: 'Your url here',
            data: formData,
            type: "POST", //ADDED THIS LINE
            // THIS MUST BE DONE FOR FILE UPLOADING
            contentType: false,
            processData: false,
            // ... Other options like success and etc
            })





            share|improve this answer




























              28












              28








              28







              I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add



              type: "POST"



              to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:



              Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.



                $.ajax({
              url: 'Your url here',
              data: formData,
              type: "POST", //ADDED THIS LINE
              // THIS MUST BE DONE FOR FILE UPLOADING
              contentType: false,
              processData: false,
              // ... Other options like success and etc
              })





              share|improve this answer















              I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add



              type: "POST"



              to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:



              Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.



                $.ajax({
              url: 'Your url here',
              data: formData,
              type: "POST", //ADDED THIS LINE
              // THIS MUST BE DONE FOR FILE UPLOADING
              contentType: false,
              processData: false,
              // ... Other options like success and etc
              })






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 27 '15 at 5:47









              Community

              11




              11










              answered Oct 13 '14 at 3:24









              supertempsupertemp

              41849




              41849























                  15














                  <form id="upload_form" enctype="multipart/form-data">


                  jQuery with CodeIgniter file upload:



                  var formData = new FormData($('#upload_form')[0]);

                  formData.append('tax_file', $('input[type=file]')[0].files[0]);

                  $.ajax({
                  type: "POST",
                  url: base_url + "member/upload/",
                  data: formData,
                  //use contentType, processData for sure.
                  contentType: false,
                  processData: false,
                  beforeSend: function() {
                  $('.modal .ajax_data').prepend('<img src="' +
                  base_url +
                  '"asset/images/ajax-loader.gif" />');
                  //$(".modal .ajax_data").html("<pre>Hold on...</pre>");
                  $(".modal").modal("show");
                  },
                  success: function(msg) {
                  $(".modal .ajax_data").html("<pre>" + msg +
                  "</pre>");
                  $('#close').hide();
                  },
                  error: function() {
                  $(".modal .ajax_data").html(
                  "<pre>Sorry! Couldn't process your request.</pre>"
                  ); //
                  $('#done').hide();
                  }
                  });


                  you can use.



                  var form = $('form')[0]; 
                  var formData = new FormData(form);
                  formData.append('tax_file', $('input[type=file]')[0].files[0]);


                  or



                  var formData = new FormData($('#upload_form')[0]);
                  formData.append('tax_file', $('input[type=file]')[0].files[0]);


                  Both will work.






                  share|improve this answer






























                    15














                    <form id="upload_form" enctype="multipart/form-data">


                    jQuery with CodeIgniter file upload:



                    var formData = new FormData($('#upload_form')[0]);

                    formData.append('tax_file', $('input[type=file]')[0].files[0]);

                    $.ajax({
                    type: "POST",
                    url: base_url + "member/upload/",
                    data: formData,
                    //use contentType, processData for sure.
                    contentType: false,
                    processData: false,
                    beforeSend: function() {
                    $('.modal .ajax_data').prepend('<img src="' +
                    base_url +
                    '"asset/images/ajax-loader.gif" />');
                    //$(".modal .ajax_data").html("<pre>Hold on...</pre>");
                    $(".modal").modal("show");
                    },
                    success: function(msg) {
                    $(".modal .ajax_data").html("<pre>" + msg +
                    "</pre>");
                    $('#close').hide();
                    },
                    error: function() {
                    $(".modal .ajax_data").html(
                    "<pre>Sorry! Couldn't process your request.</pre>"
                    ); //
                    $('#done').hide();
                    }
                    });


                    you can use.



                    var form = $('form')[0]; 
                    var formData = new FormData(form);
                    formData.append('tax_file', $('input[type=file]')[0].files[0]);


                    or



                    var formData = new FormData($('#upload_form')[0]);
                    formData.append('tax_file', $('input[type=file]')[0].files[0]);


                    Both will work.






                    share|improve this answer




























                      15












                      15








                      15







                      <form id="upload_form" enctype="multipart/form-data">


                      jQuery with CodeIgniter file upload:



                      var formData = new FormData($('#upload_form')[0]);

                      formData.append('tax_file', $('input[type=file]')[0].files[0]);

                      $.ajax({
                      type: "POST",
                      url: base_url + "member/upload/",
                      data: formData,
                      //use contentType, processData for sure.
                      contentType: false,
                      processData: false,
                      beforeSend: function() {
                      $('.modal .ajax_data').prepend('<img src="' +
                      base_url +
                      '"asset/images/ajax-loader.gif" />');
                      //$(".modal .ajax_data").html("<pre>Hold on...</pre>");
                      $(".modal").modal("show");
                      },
                      success: function(msg) {
                      $(".modal .ajax_data").html("<pre>" + msg +
                      "</pre>");
                      $('#close').hide();
                      },
                      error: function() {
                      $(".modal .ajax_data").html(
                      "<pre>Sorry! Couldn't process your request.</pre>"
                      ); //
                      $('#done').hide();
                      }
                      });


                      you can use.



                      var form = $('form')[0]; 
                      var formData = new FormData(form);
                      formData.append('tax_file', $('input[type=file]')[0].files[0]);


                      or



                      var formData = new FormData($('#upload_form')[0]);
                      formData.append('tax_file', $('input[type=file]')[0].files[0]);


                      Both will work.






                      share|improve this answer















                      <form id="upload_form" enctype="multipart/form-data">


                      jQuery with CodeIgniter file upload:



                      var formData = new FormData($('#upload_form')[0]);

                      formData.append('tax_file', $('input[type=file]')[0].files[0]);

                      $.ajax({
                      type: "POST",
                      url: base_url + "member/upload/",
                      data: formData,
                      //use contentType, processData for sure.
                      contentType: false,
                      processData: false,
                      beforeSend: function() {
                      $('.modal .ajax_data').prepend('<img src="' +
                      base_url +
                      '"asset/images/ajax-loader.gif" />');
                      //$(".modal .ajax_data").html("<pre>Hold on...</pre>");
                      $(".modal").modal("show");
                      },
                      success: function(msg) {
                      $(".modal .ajax_data").html("<pre>" + msg +
                      "</pre>");
                      $('#close').hide();
                      },
                      error: function() {
                      $(".modal .ajax_data").html(
                      "<pre>Sorry! Couldn't process your request.</pre>"
                      ); //
                      $('#done').hide();
                      }
                      });


                      you can use.



                      var form = $('form')[0]; 
                      var formData = new FormData(form);
                      formData.append('tax_file', $('input[type=file]')[0].files[0]);


                      or



                      var formData = new FormData($('#upload_form')[0]);
                      formData.append('tax_file', $('input[type=file]')[0].files[0]);


                      Both will work.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Apr 12 '16 at 10:56









                      Quentin

                      643k718671036




                      643k718671036










                      answered Aug 27 '15 at 6:47









                      chandoochandoo

                      68511120




                      68511120























                          1














                          $('#form-withdraw').submit(function(event) {

                          //prevent the form from submitting by default
                          event.preventDefault();



                          var formData = new FormData($(this)[0]);

                          $.ajax({
                          url: 'function/ajax/topup.php',
                          type: 'POST',
                          data: formData,
                          async: false,
                          cache: false,
                          contentType: false,
                          processData: false,
                          success: function (returndata) {
                          if(returndata == 'success')
                          {
                          swal({
                          title: "Great",
                          text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
                          type: "success",
                          showCancelButton: false,
                          confirmButtonColor: "#DD6B55",
                          confirmButtonText: "OK",
                          closeOnConfirm: false
                          },
                          function(){
                          window.location.href = '/transaction.php';
                          });
                          }

                          else if(returndata == 'Offline')
                          {
                          sweetAlert("Offline", "Please use other payment method", "error");
                          }
                          }
                          });



                          });





                          share|improve this answer




























                            1














                            $('#form-withdraw').submit(function(event) {

                            //prevent the form from submitting by default
                            event.preventDefault();



                            var formData = new FormData($(this)[0]);

                            $.ajax({
                            url: 'function/ajax/topup.php',
                            type: 'POST',
                            data: formData,
                            async: false,
                            cache: false,
                            contentType: false,
                            processData: false,
                            success: function (returndata) {
                            if(returndata == 'success')
                            {
                            swal({
                            title: "Great",
                            text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
                            type: "success",
                            showCancelButton: false,
                            confirmButtonColor: "#DD6B55",
                            confirmButtonText: "OK",
                            closeOnConfirm: false
                            },
                            function(){
                            window.location.href = '/transaction.php';
                            });
                            }

                            else if(returndata == 'Offline')
                            {
                            sweetAlert("Offline", "Please use other payment method", "error");
                            }
                            }
                            });



                            });





                            share|improve this answer


























                              1












                              1








                              1







                              $('#form-withdraw').submit(function(event) {

                              //prevent the form from submitting by default
                              event.preventDefault();



                              var formData = new FormData($(this)[0]);

                              $.ajax({
                              url: 'function/ajax/topup.php',
                              type: 'POST',
                              data: formData,
                              async: false,
                              cache: false,
                              contentType: false,
                              processData: false,
                              success: function (returndata) {
                              if(returndata == 'success')
                              {
                              swal({
                              title: "Great",
                              text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
                              type: "success",
                              showCancelButton: false,
                              confirmButtonColor: "#DD6B55",
                              confirmButtonText: "OK",
                              closeOnConfirm: false
                              },
                              function(){
                              window.location.href = '/transaction.php';
                              });
                              }

                              else if(returndata == 'Offline')
                              {
                              sweetAlert("Offline", "Please use other payment method", "error");
                              }
                              }
                              });



                              });





                              share|improve this answer













                              $('#form-withdraw').submit(function(event) {

                              //prevent the form from submitting by default
                              event.preventDefault();



                              var formData = new FormData($(this)[0]);

                              $.ajax({
                              url: 'function/ajax/topup.php',
                              type: 'POST',
                              data: formData,
                              async: false,
                              cache: false,
                              contentType: false,
                              processData: false,
                              success: function (returndata) {
                              if(returndata == 'success')
                              {
                              swal({
                              title: "Great",
                              text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
                              type: "success",
                              showCancelButton: false,
                              confirmButtonColor: "#DD6B55",
                              confirmButtonText: "OK",
                              closeOnConfirm: false
                              },
                              function(){
                              window.location.href = '/transaction.php';
                              });
                              }

                              else if(returndata == 'Offline')
                              {
                              sweetAlert("Offline", "Please use other payment method", "error");
                              }
                              }
                              });



                              });






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered May 23 '17 at 4:23









                              Shaiful EzaniShaiful Ezani

                              389




                              389























                                  1














                                  Actually The documentation shows that you can use XMLHttpRequest().send()
                                  to simply send multiform data
                                  in case jquery sucks






                                  share|improve this answer






























                                    1














                                    Actually The documentation shows that you can use XMLHttpRequest().send()
                                    to simply send multiform data
                                    in case jquery sucks






                                    share|improve this answer




























                                      1












                                      1








                                      1







                                      Actually The documentation shows that you can use XMLHttpRequest().send()
                                      to simply send multiform data
                                      in case jquery sucks






                                      share|improve this answer















                                      Actually The documentation shows that you can use XMLHttpRequest().send()
                                      to simply send multiform data
                                      in case jquery sucks







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jul 29 '17 at 20:23









                                      Ved Prakash

                                      95541926




                                      95541926










                                      answered Jul 29 '17 at 19:19









                                      beastar 457beastar 457

                                      295




                                      295























                                          0














                                          View:
                                          <label class="btn btn-info btn-file">
                                          Import <input type="file" style="display: none;">
                                          </label>
                                          <Script>
                                          $(document).ready(function () {
                                          $(document).on('change', ':file', function () {
                                          var fileUpload = $(this).get(0);
                                          var files = fileUpload.files;
                                          var bid = 0;
                                          if (files.length != 0) {
                                          var data = new FormData();
                                          for (var i = 0; i < files.length ; i++) {
                                          data.append(files[i].name, files[i]);
                                          }
                                          $.ajax({
                                          xhr: function () {
                                          var xhr = $.ajaxSettings.xhr();
                                          xhr.upload.onprogress = function (e) {
                                          console.log(Math.floor(e.loaded / e.total * 100) + '%');
                                          };
                                          return xhr;
                                          },
                                          contentType: false,
                                          processData: false,
                                          type: 'POST',
                                          data: data,
                                          url: '/ControllerX/' + bid,
                                          success: function (response) {
                                          location.href = 'xxx/Index/';
                                          }
                                          });
                                          }
                                          });
                                          });
                                          </Script>
                                          Controller:
                                          [HttpPost]
                                          public ActionResult ControllerX(string id)
                                          {
                                          var files = Request.Form.Files;
                                          ...





                                          share|improve this answer



















                                          • 6





                                            It is normally considered good form to provide an explanation along with an answer.

                                            – ouflak
                                            Oct 27 '16 at 19:42
















                                          0














                                          View:
                                          <label class="btn btn-info btn-file">
                                          Import <input type="file" style="display: none;">
                                          </label>
                                          <Script>
                                          $(document).ready(function () {
                                          $(document).on('change', ':file', function () {
                                          var fileUpload = $(this).get(0);
                                          var files = fileUpload.files;
                                          var bid = 0;
                                          if (files.length != 0) {
                                          var data = new FormData();
                                          for (var i = 0; i < files.length ; i++) {
                                          data.append(files[i].name, files[i]);
                                          }
                                          $.ajax({
                                          xhr: function () {
                                          var xhr = $.ajaxSettings.xhr();
                                          xhr.upload.onprogress = function (e) {
                                          console.log(Math.floor(e.loaded / e.total * 100) + '%');
                                          };
                                          return xhr;
                                          },
                                          contentType: false,
                                          processData: false,
                                          type: 'POST',
                                          data: data,
                                          url: '/ControllerX/' + bid,
                                          success: function (response) {
                                          location.href = 'xxx/Index/';
                                          }
                                          });
                                          }
                                          });
                                          });
                                          </Script>
                                          Controller:
                                          [HttpPost]
                                          public ActionResult ControllerX(string id)
                                          {
                                          var files = Request.Form.Files;
                                          ...





                                          share|improve this answer



















                                          • 6





                                            It is normally considered good form to provide an explanation along with an answer.

                                            – ouflak
                                            Oct 27 '16 at 19:42














                                          0












                                          0








                                          0







                                          View:
                                          <label class="btn btn-info btn-file">
                                          Import <input type="file" style="display: none;">
                                          </label>
                                          <Script>
                                          $(document).ready(function () {
                                          $(document).on('change', ':file', function () {
                                          var fileUpload = $(this).get(0);
                                          var files = fileUpload.files;
                                          var bid = 0;
                                          if (files.length != 0) {
                                          var data = new FormData();
                                          for (var i = 0; i < files.length ; i++) {
                                          data.append(files[i].name, files[i]);
                                          }
                                          $.ajax({
                                          xhr: function () {
                                          var xhr = $.ajaxSettings.xhr();
                                          xhr.upload.onprogress = function (e) {
                                          console.log(Math.floor(e.loaded / e.total * 100) + '%');
                                          };
                                          return xhr;
                                          },
                                          contentType: false,
                                          processData: false,
                                          type: 'POST',
                                          data: data,
                                          url: '/ControllerX/' + bid,
                                          success: function (response) {
                                          location.href = 'xxx/Index/';
                                          }
                                          });
                                          }
                                          });
                                          });
                                          </Script>
                                          Controller:
                                          [HttpPost]
                                          public ActionResult ControllerX(string id)
                                          {
                                          var files = Request.Form.Files;
                                          ...





                                          share|improve this answer













                                          View:
                                          <label class="btn btn-info btn-file">
                                          Import <input type="file" style="display: none;">
                                          </label>
                                          <Script>
                                          $(document).ready(function () {
                                          $(document).on('change', ':file', function () {
                                          var fileUpload = $(this).get(0);
                                          var files = fileUpload.files;
                                          var bid = 0;
                                          if (files.length != 0) {
                                          var data = new FormData();
                                          for (var i = 0; i < files.length ; i++) {
                                          data.append(files[i].name, files[i]);
                                          }
                                          $.ajax({
                                          xhr: function () {
                                          var xhr = $.ajaxSettings.xhr();
                                          xhr.upload.onprogress = function (e) {
                                          console.log(Math.floor(e.loaded / e.total * 100) + '%');
                                          };
                                          return xhr;
                                          },
                                          contentType: false,
                                          processData: false,
                                          type: 'POST',
                                          data: data,
                                          url: '/ControllerX/' + bid,
                                          success: function (response) {
                                          location.href = 'xxx/Index/';
                                          }
                                          });
                                          }
                                          });
                                          });
                                          </Script>
                                          Controller:
                                          [HttpPost]
                                          public ActionResult ControllerX(string id)
                                          {
                                          var files = Request.Form.Files;
                                          ...






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Oct 27 '16 at 19:23









                                          Vkl125Vkl125

                                          6418




                                          6418








                                          • 6





                                            It is normally considered good form to provide an explanation along with an answer.

                                            – ouflak
                                            Oct 27 '16 at 19:42














                                          • 6





                                            It is normally considered good form to provide an explanation along with an answer.

                                            – ouflak
                                            Oct 27 '16 at 19:42








                                          6




                                          6





                                          It is normally considered good form to provide an explanation along with an answer.

                                          – ouflak
                                          Oct 27 '16 at 19:42





                                          It is normally considered good form to provide an explanation along with an answer.

                                          – ouflak
                                          Oct 27 '16 at 19:42


















                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f21044798%2fhow-to-use-formdata-for-ajax-file-upload%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          這個網誌中的熱門文章

                                          Tangent Lines Diagram Along Smooth Curve

                                          Yusuf al-Mu'taman ibn Hud

                                          Zucchini