Skip to content
the poor coder

upload file using ajax

Poor Man
Published
Reading time
2 min read
On this page

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.

Text

      <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.

Text

      $(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.

Text

      <?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:

Text

      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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC