简体   繁体   中英

AJAX post sending data serialize and image data

I have a problem in post request in AJAX submitting form serialize and my image data array. How can i do this?

Here is my code:

I want to send this data:

var Imagedata = new FormData();
jQuery.each(jQuery('#addfiles')[0].files, function(i, file) {
  data.append('file-'+i, file);
});

and

$("#editProd").serialize()

Here is what I did: data: $("#editProd").serialize()+Imagedata,

I have this as fullcode :

function ProductAjax(e) {
  e.preventDefault();

  var Imagedata = new FormData();
  jQuery.each(jQuery('#addfiles')[0].files, function(i, file) {
    data.append('file-'+i, file);
  });

  $.ajax({         
    url: "{{ route('admin.editProduct') }}",        
    type: "POST",
    data: $("#editProd").serialize()+Imagedata,
    dataType: "JSON",
    success: function(data) {
      if($.isEmptyObject(data.error)){
        $('.print-error-msg-addcat').removeClass('alert alert-danger');
        $('.print-error-msg-addcat').addClass('alert alert-success');
        $('.print-error-msg-addcat').find("ul").html('');
        $('.print-error-msg-addcat').css('display','block');
        $(".print-error-msg-addcat ul").append('<li class="tick">'+data.success+'</li>');
        $('#frmAddcategory')[0].reset();
        location.reload();
      }else{
        printErrorMsgEditprod(data.error);
      }
    }
  }); 
}

Am I doing right? Any suggestions?

Look at the code and comments below:

function ProductAjax(e) {
  e.preventDefault();

  var formData = new FormData($("#editProd")[0]); //assuming this object is a form element.
  //the FormData object allows a form element to be passed to the constructor. The new instance
  //will have all the form input fields already appended.
  //if not a form element you need to append every input seperately using jQuery.serializeArray

  jQuery.each(jQuery('#addfiles')[0].files, function(i, file) {
    formData.append('file-'+i, file);
  });


  $.ajax({         
    url: "{{ route('admin.editProduct') }}",        
    type: "POST",
    data: formData, //send the formData object containing all the form input.
    dataType: "JSON",
    success: function(data) {
      if($.isEmptyObject(data.error)){
        $('.print-error-msg-addcat').removeClass('alert alert-danger');
        $('.print-error-msg-addcat').addClass('alert alert-success');
        $('.print-error-msg-addcat').find("ul").html('');
        $('.print-error-msg-addcat').css('display','block');
        $(".print-error-msg-addcat ul").append('<li class="tick">'+data.success+'</li>');
        $('#frmAddcategory')[0].reset();
        location.reload();
      }else{
        printErrorMsgEditprod(data.error);
      }
    }
  }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM