How to upload a file with JavaScript and PHP

File uploading option on a website is common. But to make it work from scratch seems a very difficult task and sometimes we have to waste lots of time to figure out if things do not work properly.

In this tutorial, we will upload the file using javascript and PHP with a simple function. Javascript will be used to initiate the function and PHP to upload the file on the server. Once the setup is done, you do not need to reload the file to upload one and more images simultaneously.

HTML code to upload file

First, we need to create a file with the below code. The first input tag would be file to select the file. The second input tag would be button to initiate the javascript function.

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

Javascript code to upload file

Create uploadFile() function which will be called on the Upload button click in HTML.

// 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"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.");
              alert("File not uploaded.");

      // Send request with data

      alert("Please select a file");


PHP code to upload file

Make a ajaxfile.php file and an upload folder to store the uploaded files.

PHP will check the file extensions and only allow Pdf, Doc, Docx, Jpg, Png, Jpeg to be uploaded. If the user will try to upload other then this extension file the function will exit with response ‘0’;


   // file name
   $filename = $_FILES['file']['name'];

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

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

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

   $response = 0;
      // Upload file
         $response = 1;

   echo $response;