I have 2 forms:
Form A contains field name, age, address, email and a hidden text field for the names of images which are going to be uploaded in form B.
Form B contain an input type File so users can browse and select their photos.
I used Jquery to trigger an function upload those images after they are selected.
I'm stuck at the step passing the selected images array to the PHP file that handles upload progress via AJAX.
I searched but there were no samples for my problem. I appreicate any help.
<form action="upload_img.php" name="form_B" method="POST" enctype="multipart/form-data">
Select images: <input type="file" name="selected_imgs[]" id="selected_imgs" multiple>
</form>
<script type="text/javascript">
$(function() {
$("input:file").change(function (){
ajax_upload();
});
});
</script>
You can try below code
function uploadFile(){
var file = $('#filetoupload');
var valid_extensions = /(\.jpg|\.jpeg|\.gif|\.doc|\.xls|\.txt|\.rtf|\.pdf)$/i;
var isvalid = true;
//for every file...
var input = document.getElementById('filetoupload');
for (var x = 0; x < input.files.length; x++) {
if(!valid_extensions.test(input.files[x].name)){
isvalid = false;
}
}
if(isvalid == true ){
var formData = new FormData();
for (var x = 0; x < input.files.length; x++) {
formData.append("filetoupload[]",input.files[x]);
}
$.ajax({
url: 'localhost/upload.php', //server script to process data
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success:function (data){
alert("File Uploaded");
// data.src return from your server
// so you can display image in page using <img> tag
},
error:function (data){
alert("Error!");
}
});
}else{
alert("File format not supported!");
return false;
}
return true;
}