How to upload file with JavaScript and PHP

File uploading is a basic requirement in a website. It is done using a server-side script.

Requires to reload the page after form submission to execute the script.

With AJAX client-side script is interact with the server-side script and performs the action without page reload.

In this tutorial, I show how you can upload a file using JavaScript AJAX, and PHP.

How to upload file with JavaScript and PHP


Contents

  1. HTML
  2. PHP
  3. JavaScript
  4. Output
  5. Conclusion

1. HTML

Create a file and button element. Added onclick event on the button which calls uploadFile() function.

Completed Code

<div >
  <input type="file" name="file" id="file">
  <input type="button" id="btn_uploadfile" 
     value="Upload" 
     onclick="uploadFile();" >
</div>

2. PHP

Create a ajaxfile.php file and an upload folder to store files.

Check if $_FILES Array is set or not. If set then assign $_FILES['file']['name'] to $filename, file name with upload location in $location variable.

Get the file extension and assign valid file extensions in $valid_ext Array.

Check if file extension exists in $valid_ext Array. If exists then upload the file and assign 1 to $response if successfully uploaded.

Return $response.

Completed Code

<?php

if(isset($_FILES['file']['name'])){
   // file name
   $filename = $_FILES['file']['name'];

   // Location
   $location = 'upload/'.$filename;

   // file extension
   $file_extension = pathinfo($location, PATHINFO_EXTENSION);
   $file_extension = strtolower($file_extension);

   // Valid extensions
   $valid_ext = array("pdf","doc","docx","jpg","png","jpeg");

   $response = 0;
   if(in_array($file_extension,$valid_ext)){
      // Upload file
      if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
         $response = 1;
      } 
   }

   echo $response;
   exit;
}

3. JavaScript

Create uploadFile() function which calls on the Upload button click.

Read files of a file element. If a file is selected then create an object of FormData otherwise, alert "Please select a file" message.

Append files[0] to 'file' key in formData.

To send AJAX request create an object of XMLHttpRequest. With open() method set request method to "POST" and AJAX file path.

Handle AJAX successful callback with onreadystatechange() method. Assign this.responseText in response variable. If response == 1 then alert "Upload successfully." message otherwise, alert "File not uploaded." message.

Pass formData object with send() method.

Completed Code

// Upload file
function uploadFile() {

   var files = document.getElementById("file").files;

   if(files.length > 0 ){

      var formData = new FormData();
      formData.append("file", files[0]);

      var xhttp = new XMLHttpRequest();

      // Set POST method and ajax file path
      xhttp.open("POST", "ajaxfile.php", true);

      // call on request changes state
      xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {

           var response = this.responseText;
           if(response == 1){
              alert("Upload successfully.");
           }else{
              alert("File not uploaded.");
           }
         }
      };

      // Send request with data
      xhttp.send(formData);

   }else{
      alert("Please select a file");
   }

}

4. Output


5. Conclusion

Send the file instance using FormData object and in the AJAX file access it using $_FILES Array.

You can view this tutorial to know how to upload a file using jQuery AJAX.

How to upload multiple files with JavaScript and PHP

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

4 thoughts on “How to upload file with JavaScript and PHP”

  1. This appears to work nicely when using just a standard HTML document. BUT, if you try to implement it, in a wordpress plugin, with the plugin generating the same HTML code AND load the ajax file into the same folder as the plugin, it fails. I have tried relative path and complete URL.

    do you know how to make the call work within a wordpress environment?:

    var xhttp = new XMLHttpRequest();
    var ajaxpath = “ajaxfile.php”; /* error 404 not found*/
    /*var ajaxpath = “https://virtualhorsesport.com/wp-content/plugins/mmd-virtual-show/ajaxfile.php”; error 500*/
    /* var ajaxpath = “ajaxfile.php”; 404 Error Not found*/

    // Set POST method and ajax file path
    xhttp.open(“POST”, ajaxpath, true); <<< FAILS

    Reply
  2. actually it doesn’t within a plugin. As a separate html file yes, but not as a part of the page system. The WordPress plugin via wordpress will not find the ajax file and it will give a “file not found” error code of 404.

    I fixed the problem using add_action and thus invoked that process which the ajax code is NOT a separate file, but a piece of code that is called. Now it works.

    Reply

Leave a Comment