Overview:
Uploading multiple files to a server is a common requirement in web development. jQuery's '.submit()' and '.ajax()' methods provide a convenient approach for submitting forms and sending data to the server asynchronously. This article addresses how to use these methods to facilitate multiple-file upload.
Form HTML:
The HTML form should include multiple file input fields, an "Add More Files" button, and a submit button. When the "Add More Files" button is clicked, additional file input fields are added dynamically.
<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">
JavaScript for Dynamic File Input Addition:
The JavaScript code uses jQuery to add additional file input fields when the "Add More Files" button is clicked.
$(document).ready(function(){ $('.add_more').click(function(e){ e.preventDefault(); $(this).before("<input name='file[]' type='file'>"); }); });
Upload Script:
The server-side PHP script ('upload.php') handles the file upload process, including validation and saving to the target directory. It assumes a hierarchical directory structure to organize the uploaded files.
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 />"; } }
jQuery for AJAX File Submission:
Finally, the '.submit()' and '.ajax()' methods are used to bind an event listener to the submit button. When clicked, an AJAX request is sent to the 'upload.php' script, and the uploaded file data is included in the request using a FormData object. jQuery's 'success' function handles the server response.
$('body').on('click', '#upload', function(e){ e.preventDefault(); var formData = new FormData($(this).parents('form')[0]); $.ajax({ url: 'upload.php', type: 'POST', xhr: function() { var myXhr = $.ajaxSettings.xhr(); return myXhr; }, success: function (data) { alert("Data Uploaded: "+data); }, data: formData, cache: false, contentType: false, processData: false }); return false; });
By implementing this approach, you can effectively upload multiple files asynchronously using PHP, jQuery, and AJAX.
The above is the detailed content of How to Use jQuery's `.submit()` and `.ajax()` for Asynchronous Multiple File Uploads?. For more information, please follow other related articles on the PHP Chinese website!