In my code there is a single form that contains 2 input elements:
text input and
file input (which will contain an image).
I am appending each file input on button click and want to upload all images in an ajax call, but in my PHP file I only get the final image and value of text input.
My html and jquery code are as follows:
HTML code
<html>
<body>
<form name="ajax_image" id="ajax_image" method="post">
<input type="text" name="project_name" id="project_name" placeholder="Project Name" /><br/><br/>
<input type="text" name="project_duration" id="project_duration" placeholder="Project Duration" /><br/><br/>
<div id="image_uploads">
<input type="file" name="project_image[]" class="project_image" placeholder="Project Image" />
<input type="button" name="add_upload" id="add_upload" value="+" />
<br/><br/>
</div>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Jquery code
<script>
$(document).ready(function () {
var count=0;
$("#add_upload").click(function(){
var input = '<input type="file" name="project_image[]" class="project_image" placeholder="Project Image"/><br/><br/>'
$("#image_uploads").append(input);
count++;
});
$("#ajax_image").submit(function (event) {
event.preventDefault();
var data = new FormData();
for(var j=0 ; j<= count ; j++)
{
// alert(j);
$.each($(".project_image")[j].files, function (i, file)
{
data.append(i, file);
});
}
$.each($('#ajax_image').serializeArray(), function (i, obj) {
data.append(obj.name, obj.value)
});
$.ajax({
url: "http://localhost/hetal/multi_image_php_ajax.php",
type: "POST",
data: data,
processData: false,
contentType: false,
success: function () {
alert('Form Submitted!');
},
error: function () {
alert("error in ajax form submission");
}
});
});
});
</script>
PHP file
<?php
print_r($_POST);
print_r($_FILES);
?>
<input type="file" name="project_image[]" class="project_image" placeholder="Project Image" multiple />to get multiple files?