How to Upload file using JavaScript and PHP

How to Upload file using JavaScript and PHP

In this tutorial, I show how you can upload a file using JavaScript AJAX 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.

Contents

  1. HTML
  2. PHP
  3. JavaScript
  4. 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 image 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. Conclusion

You have to send the file instance using FormData object and in the AJAX file access it using $_FILES Array.

If you found this tutorial helpful then don't forget to share

javascript php html ajax

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Cannot send array to php via AJAX?

Well I followed&nbsp;<a href="https://stackoverflow.com/questions/9001526/send-array-with-ajax-to-php-script" target="_blank">this</a>&nbsp;question, but cannot send array to php it returns me always empty:

Autocomplete Textbox with Javascript, PHP and MySQL

In this guide, we will walk through how to add autocomplete to a textbox, with the help of jQuery and also an alternative that works with just vanilla Javascript.

Encode data in php and uncompress in Javascript (ajax)

In order to reduce the size of my json file, I wanted to zip it. Hence, I am trying to compress json data file sent from php server :

Countdown with HTML, CSS, and JavaScript / How to create JavaScript Countdown

Countdown with HTML, CSS, and JavaScript / How to create JavaScript Countdown. W will build a Responsive Website with HTML, CSS, and JavaScript

Ajax (jQuery) PHP Script // move_uploaded_file-problem

I'm working on a&nbsp;<strong>gallery-upload</strong>-function with