upload file using ajax

How to Upload File Using AJAX

If you want to upload a file without refreshing the page, you can use AJAX. AJAX stands for Asynchronous JavaScript and XML. It allows you to send and receive data from a server without reloading the entire page.

Step 1: Create HTML Form

Create an HTML form with the necessary file input field. Make sure to add enctype="multipart/form-data" to the form tag.


      <form id="myForm" enctype="multipart/form-data">
        <input type="file" name="myFile">
        <button type="submit">Upload</button>
      </form>
    

Step 2: Create AJAX Request

Create a JavaScript function that handles the AJAX request. This function should listen for the form submission event, prevent the default form submission, and send the form data to the server using AJAX. You can use jQuery or plain JavaScript for this.


      $(document).ready(function() {
        $('#myForm').submit(function(event) {
          event.preventDefault();
          var formData = new FormData(this);
          $.ajax({
            url: 'upload.php', //replace with your upload PHP script
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
              console.log(response);
            }
          });
        });
      });
    

The FormData object is used to capture all the form data, including the file. The processData and contentType options are set to false to prevent jQuery from processing the data and setting the content type automatically.

Step 3: Handle Server-Side Upload

On the server side, you need to handle the file upload in your PHP script. You can use the $_FILES superglobal to access the file data.


      <?php
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["myFile"]["name"]);
        move_uploaded_file($_FILES["myFile"]["tmp_name"], $target_file);
        echo "File uploaded successfully!";
      ?>
    

The above code moves the uploaded file to a directory named "uploads" and echoes a success message.

Alternative Method: Using XMLHttpRequest

If you want to use pure JavaScript without jQuery, you can use the XMLHttpRequest object. Here's an example:


      var form = document.getElementById('myForm');
      form.addEventListener('submit', function(event) {
        event.preventDefault();
        var formData = new FormData(form);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'upload.php', true);
        xhr.onload = function() {
          console.log(this.responseText);
        };
        xhr.send(formData);
      });
    

This code uses the XMLHttpRequest object to send the form data to the server. The onload function is called when the request is complete, and it logs the server response.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe