dapo dapo - 2 months ago 7
Ajax Question

Sending multiple data through jquery ajax

I am building a form to process text input, multiple check boxes and 4 images. currently I am to process the check boxes using the each function to put all the values of the checkboxes in an array before sending it through ajax. Now the problem is that I can't send the images with ajax too. And also I can't access the images too.

Code:

$(document).ready(function () {
//alert("this page works");
$('#uploadProperty').on('submit',function (e){
e.preventDefault();

var hname = $('#hname').val();
var location = $('#location').val();
var htype = $('#htype').val();
var rooms = $('#rooms').val();
var price = $('#price').val();
var hdetails = $('#hdetails').val();
var feature = [];
$('.feature').each(function() {
if($(this).is(":checked")){
feature.push($(this).val());
}
});
// if (feature.length == 0)
// alert("Select atleast 1 Feature");
// else{
// feature = feature.toString();
// alert(feature);
// }
var file1 = $('#file4').val();
//alert(file1);
$.ajax({
url : 'core/upload.php',
type : 'POST',
data : new FormData(),
contentType : false,
processData : false,
success : function (ep){
alert(ep);
}
});

});
});

Answer

So if i got it right, you want to fill the FormData object. Because currently it's blank. You can use append method:

    var formData = new FormData();
    var $myField = $('#myField');
    formData.append('myField', $myField.val());

To append file:

    var $fileField = $('#fileField');
    var myFile = $fileField.get(0).files[0];
    formData.append('myFile', myFile);

To append multiplie files you should set the name properly:

    formData.append('myFile[]', myFileFirst);
    formData.append('myFile[]', myFileSecond);

Check it here: Uploading multiple files using formData()

Also, you can grab the whole form data through constructor:

    var form = $('form').get(0);
    var formData = new FormData(form);
Comments