File uploading is a basic requirement in a website. It is done using a server-side script. Requires reloading 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 file using JavaScript AJAX and PHP.
Table of Content
- Create an HTML Form for Submitting Files
- PHP code for handling the uploaded file
- JavaScript code for uploading the file
- Output
- Conclusion
1. Create an HTML Form for Submitting Files
Create a file and button element. Added onclick
event on the button which calls uploadFile()
function.
<div > <input type="file" name="file" id="file"> <input type="button" id="btn_uploadfile" value="Upload" onclick="uploadFile();" > </div>
2. PHP code for handling the uploaded file
Create 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.
Read the file extension and assign it to $file_extension.
Assign valid file extensions to $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
.
<?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 code for file upload
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
to response
variable. If response == 1
then alert "Upload successfully."
message otherwise, alert "File not uploaded."
message.
Pass formData
object with send()
method.
// 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. Output
5. 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.
Additionally, if you are interested in uploading multiple files using JavaScript and PHP then you can view this tutorial.
If you found this tutorial helpful then don't forget to share.