I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload.
Here is my HTML form :
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" id="upload" value="Upload File" />
</form>
Here is the JavaScript :
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' />");
});
});
Here is the code for processing file upload :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Any suggestions on how I should write my '.submit()' function will be really helpful.
HTML
Javascript
for ajax upload
PHP
Please use the script above script for ajax upload. It will work
HTML
Javascript
PHP
Finally I have found the solution by using the following code:
My solution
jQuery code