Send FormData and String Data Together Through JQuery AJAX?
var fd = new FormData();var file_data = $('input[type="file"]')[0].files; // for multiple filesfor(var i = 0;i<file_data.length;i++){ fd.append("file_"+i, file_data[i]);}var other_data = $('form').serializeArray();$.each(other_data,function(key,input){ fd.append(input.name,input.value);});$.ajax({ url: 'test.php', data: fd, contentType: false, processData: false, type: 'POST', success: function(data){ console.log(data); }});
Added a for
loop and changed .serialize()
to .serializeArray()
for object reference in a .each()
to append to the FormData
.
well, as an easier alternative and shorter, you could do this too!!
var fd = new FormData();var file_data = object.get(0).files[i];var other_data = $('form').serialize(); //page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+IDfd.append("file", file_data);$.ajax({ url: 'add.php?'+ other_data, //<== just add it to the end of url *** data: fd, contentType: false, processData: false, type: 'POST', success: function(data){ alert(data); }});
I always use this.It send form data using ajax
$(document).on("submit", "form", function(event){ event.preventDefault(); var url=$(this).attr("action"); $.ajax({ url: url, type: 'POST', data: new FormData(this), processData: false, contentType: false, success: function (data, status) { } });});