Home > Backend Development > PHP Tutorial > How to Use jQuery\'s `.submit()` and `.ajax()` for Asynchronous Multiple File Uploads?

How to Use jQuery\'s `.submit()` and `.ajax()` for Asynchronous Multiple File Uploads?

DDD
Release: 2024-11-27 05:36:14
Original
698 people have browsed it

How to Use jQuery's `.submit()` and `.ajax()` for Asynchronous Multiple File Uploads?

Submitting Files via AJAX Using jQuery's '.submit()' and '.ajax()'

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">
Copy after login

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'>");
    });
});
Copy after login

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 />";
    }
}
Copy after login

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;
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template