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.

 


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.

Complete 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

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.

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.
 

Related Posts