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

Contents

HTML

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>                       
<div class="form-group submit_div"> 
	<button onclick="uploadFile();" class="btn  btn-info btn-md">Upload</button>
</div> 
<div class="form-group"> 
	<span class="message"></span>
</div> 

JavaScript

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
            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");
        }

}
</script>   

PHP

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;
     if(in_array($file_extension,$valid_ext)){
          // Upload file
          if(move_uploaded_file($_FILES['file']['tmp_name'],$uploadlocation)){
            // if file upload then return 1.
            $response = 1;
            }else{
            // if file not upload then return 2.
              $response = 2;
            }
      }else{
         // if file not Valid file extensions then return 2.
           $response = 0;
      }
      return $response;
      exit();
}

Output

Download source code

Be First to Comment

Leave a Reply

Your email address will not be published.