In this article, we will learn how to upload a file with JavaScript and PHP. we are using image upload without reloading the page in this example. so here we are using the javascript ajax.
If you want to do without ajax upload image then you can do it. but when you need to image upload without reloading the page then we are using this type of example. .so you can see our example.
we need to create the input file and take the button. after then we will pass the onclick button attribute. when visitors click a button then file will be sent to the server.
<div >
<input type="file" name="file" id="file">
<input type="button" id="btn_uploadfile"
value="Upload"
onclick="uploadFile()" >
</div>
When visitors click on a button then this function will be called.
// 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", "file_upload.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");
}
}
file_upload.php
<?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;
}
?>