The Wayback Machine - https://web.archive.org/web/20240603161301/https://www.geeksforgeeks.org/asynchronous-file-transfer-in-ajax/
Open In App

Asynchronous file transfer in AJAX

Last Updated : 27 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

To transfer Files in jQuery using Ajax we follow the following steps and an example demonstrating the same:

  1. Using HTML5, we can upload files using a form. The content-type is specified as multipart/form-data.
  2. An input field is created for files to be uploaded with input type as file.
  3. We can use the multiple attribute to allow more than one file to be uploaded and can also filter out file types by using the accept attribute.
  4. On upload a listener appends the uploaded files to a file list iteratively.
  5. With the submit button an ajax request is created and the form data is sent across to the specified url.

Example: Here consider the case of sending videos asynchronously.

  • We have created an HTML5 form as below:




    <div>
        <form method="POST" enctype="multipart/form-data"
                action="" id="capt">
            <div class="form-group">
                <label>Select Files</label>
                <input type="file" id="file" name="file[]"
                    accept="video/*" class="form-control"
                    multiple="multiple" required>
            </div>
      
            <input type="submit" class="btn btn-info"
                    value="Submit">
        </form>
    </div>

    
    

  • Using jQuery, we create appropriate methods for uploading and sending file asynchronously.




    var fileList = [];
      
    $('#file').on('change', function (event) {
      
        fileList = [];
      
        // Append files to fileList
        for (var i = 0; i < this.files.length; i++) {
            fileList.push(this.files[i]);
        }
    });
      
    sendFile = function (file) {
      
        // Create Ajax Request
        $.ajax({
            url: 'notify.php',
            type: 'POST',
            data: new FormData($('form')[0]),
            cache: false,
            contentType: false,
            processData: false
        });
    }
      
    $('#capt').on('submit', function (event) {
        event.preventDefault();
          
        //Asynchronous Transfer
        sendFile(file);
    });

    
    

  • For the sake of demonstrating the output, we create a minimal PHP file as below:




    <?php
      
    $video = $_FILES['file']['name'];
    foreach($video as $vd){
        echo $vd."<br>";
    }
    ?>

    
    

  • Output(notify.php):



Similar Reads

How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests ?
In this article, we are going to see how we can use jQuery's ajax() function to call backend function asynchronously or in other words HTTP Requests. AJAX is a set of web development techniques used by client-side frameworks and libraries to make asynchronous HTTP calls to the server. AJAX stands for "Asynchronous JavaScript and XML". In simpler wo
4 min read
What is an asynchronous request in AJAX ?
In this article, we will have a deep look into Asynchronous AJAX requests. Basically, AJAX provides two types of requests namely Synchronous AJAX and Asynchronous AJAX. Asynchronous requests in AJAX don't wait for a response from the server whereas synchronous waits for the response. When asynchronous requests are running JavaScript continues to ex
3 min read
Difference between synchronous and asynchronous requests in jQuery Ajax
In this article, we'll look at the differences between synchronous and asynchronous JQuery Ajax requests. JQuery provides several built-in methods for requesting data from the server: HTML, TXT, JSON, or String data can be requested. $.ajax() is a popular JQuery method for making synchronous and asynchronous requests to the server or web pages. Wha
5 min read
Difference between Server-Side AJAX framework and Client-side AJAX framework ?
The article focuses on discussing the differences between the Server-side AJAX framework and the Client-side AJAX framework. The following topics will be discussed here: What is a Server-side AJAX framework?What is a Client-side AJAX framework?Server-side AJAX framework vs Client-side AJAX framework Let's start discussing each of these topics in de
3 min read
How to get return text from PHP file with ajax ?
In this article, we will see how to get return the text from the PHP file with ajax. Ajax is an acronym for Asynchronous JavaScript and XML is a series of web development techniques that build asynchronous web applications using many web technologies on the client-side. Without reloading the web page, AJAX enables you to send and receive informatio
2 min read
How to load a JSON object from a file with ajax?
Loading a JSON object from a file using AJAX involves leveraging XMLHttpRequest (XHR) or Fetch API to request data from a server-side file asynchronously. By specifying the file's URL and handling the response appropriately, developers can seamlessly integrate JSON data into their web applications. This method enables dynamic loading of data withou
3 min read
How asynchronous JavaScript code gets executed in browser ?
Functions or operations that are running in parallel with the other functions or operations are called the asynchronous functions or operations in JavaScript. Asynchronous functions use Callback Functions that get executed later. Let us see an example that demonstrates this: C/C++ Code setTimeout(function greet() { console.log(&quot;Welcome to Geek
3 min read
Explain Asynchronous vs Deferred JavaScript
Generally, when we use a script tag to load any JavaScript code, the HTML parsing is paused by the browser when it encounters the script tag and it starts to download the JavaScript file first. The HTML elements script tag will not be executed until the browser is done with downloading the script and executing it. The browser waits till the script
3 min read
How to create an Asynchronous function in Javascript?
JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot; /&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body
6 min read
How to write asynchronous function for Node.js ?
The asynchronous function can be written in Node.js using 'async' preceding the function name. The asynchronous function returns an implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event loop. Async functions will always return a value. Await function can be used inside the asynchronous funct
2 min read