Problem when passing an image and a checkbox group through ajax

0

Good morning, I have a problem when passing the parameters of a file type form and a checkbox group through ajax.

My code is as follows

$("#form_img").submit(function(event){

  $('#p2').show();
 
  //disable the default form submission
  event.preventDefault();
 
  //grab all form data  
  var formData = new FormData($(this)[0]);

  var buckets = new Array();
        $( "input[name='checkpoint[]']:checked" ).each( function() {
                buckets.push( $( this ).val() );
        } );
 
  $.ajax({
    url: 'img_point/',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (returndata) {
      //alert(returndata);
      $('.resulttemp').html(returndata);
       alertify.warning('Por favor espere…');
      $('#p2').hide();
    }
  });
 
  return false;
});

As I do to pass the variable buckets using the ajax code, I tried with the data method: {buckets: buckets, formData: formData}, but it does not work, I appreciate all the help possible. Thank you very much.

    
asked by Andrews 09.01.2017 в 18:09
source

2 answers

0

Try using FormData.append() .

So for example:

$("input[name='checkpoint[]']:checked").each(function() {
  formData.append("buckets[]", this.value);
});
    
answered by 09.01.2017 / 18:38
source
1

Hello this is the final code you use:

$("#form_img").submit(function(event){

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

  $("input[name='checkpoint[]']:checked").each(function() {
    formData.append("buckets[]", this.value);
  });
 
  $.ajax({
    url: 'img_point',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (returndata) {
  
      $('.response').html(returndata);
      
    }
  });
 
  return false;
});
 <form enctype="multipart/form-data" id="form_img"  method="post">

   <input type="file"  id="file" name="userfile" required>
   <input type='checkbox' name='checkpoint[]' value='1'>
   <input type='checkbox' name='checkpoint[]' value='2'>
   <input type='checkbox' name='checkpoint[]' value='3'>

   <input  type="submit" value="Cambiar"/>
 
</form>

<div class='response'></div>
    
answered by 07.03.2017 в 16:24