File upload using JavaScript, Ajax, and PHP With an Example

In this tutorial, we will learn How to Upload a File using JavaScript and PHP with an example.

File upload using JavaScript and PHP



Creating a index.htmlfile.

In it create a one file type elements for select a file and a button. Call a uploadFile() function on button click to call a AJAX.

<div class="form-group">
	<label for="file" class="text-info">Select file:</label><br>
	<input type="file" id="file-upload" name="uploadedFile" class="form-control">
<div class="form-group submit_div"> 
	<button onclick="uploadFile();" class="btn  btn-info btn-md">Upload</button>
<div class="form-group"> 
	<span class="message"></span>


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

Create a form_data object and Append files[0] to ‘file’ key in form_data.

we use the open() method of the XMLHttpRequest object to send a request to server and Handle AJAX successful callback with onreadystatechange() method.

We will alert a message according Ajax response.

<script type="text/javascript">
	function uploadFile() {
        var files = document.getElementById("file-upload").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");



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

Check file is set or not, if file is set then Read file extension and Initialized valid $valid_extensions Array.

Check upload file extension is in $valid_extensions Array or not. If exists then upload a file. Return $responsevariable.

if(isset($_FILES['file']['name']) ){  
    // file name
    $filename = $_FILES['file']['name'];  
    // Location
    $uploadlocation = 'upload/'.$filename;
    // get file extension
    $file_extension = pathinfo($uploadlocation, PATHINFO_EXTENSION);
    $file_extension = strtolower($file_extension);
    // Valid file extensions
    $valid_ext = array("pdf","doc","docx","jpg","png","jpeg","xls");
    $response = 0;
          // Upload file
            // if file upload then return 1.
            $response = 1;
            // if file not upload then return 2.
              $response = 2;
         // if file not Valid file extensions then return 2.
           $response = 0;
      return $response;


Download source code

Be First to Comment

Leave a Reply

Your email address will not be published.