Mr. Developer Mr. Developer - 4 months ago 240
Ajax Question

Browsers are giving different jquery errors in the result of code

I'm tying to validate and upload images using multiple accept input using jquery, ajax and php. I added validation function which is working properly, but form does not submitting, also chrome and firefox showing different errors in console.

HTML



<form id="promotionImageForm_<?php echo $row['pm_id']; ?>" autocomplete="off" enctype="multipart/form-data">
<label>Add More Images</label>
<input type="file" name="pm_image[]" class="form-control" multiple="multiple" id="pmMultiImgs_<?php echo $row['pm_id']; ?>" />
<input type="hidden" name="pm_id" value="<?php echo $row['pm_id']; ?>" />
<input type="hidden" name="uploadImageByID" value="uploadImageByID" />
<button type="button" onclick="return multiImageUpload(<?php echo $row['pm_id']; ?>);" id="pmMultibTn" />Add</button>
</form>


JS Function



function uploadImageByID(formData){
$.ajax({
type:'POST',
url:'response.php',
data:formData,
dataType:"json",
success: function(response){
$(".pmImgPopNoti").remove();
if(response.success){
$(".pmRes_"+promotionImageID).prepend('<div id="login-alert" class="alert alert-success pmImgPopNoti col-sm-12">'+response.success+'</div>');
}
if(response.error){
$(".pmRes_"+promotionImageID).prepend('<div id="login-alert" class="alert alert-danger pmImgPopNoti col-sm-12">'+response.error+'</div>');
}
}
});
}
function multiImageUpload(pmID){
$('#promotionImageForm_'+pmID).validate();
$('#pmMultiImgs_'+pmID).each(function() {
$(this).rules("add", {
required: true,
accept: "image/jpeg, image/pjpeg, image/png",
messages: {
accept: "Only jpeg, jpg or png images"
}
});
});
if ($('#promotionImageForm_'+pmID).valid()) {
var formDetail = $('#promotionImageForm_'+pmID);
var formData = new FormData(formDetail);
uploadImageByID(formData);
return false;
}
}


Chrome Showing This Error


Uncaught TypeError: Illegal invocation


FireFox Showing This Error


TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
var formData = new FormData(formDetail);


Can anyone guide me how can i fix this error. I would like to appreciate if someone guide me. Thank You

Answer

The FormData object constructor expects a form element, not a jQuery object containing a form. Try this:

if ($('#promotionImageForm_'+pmID).valid()) {
    var formDetail = $('#promotionImageForm_' + pmID);
    var formData = new FormData(formDetail[0]); // note [0] here
    uploadImageByID(formData);
    return false;
}