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

File upload using Ajax, jQuery, and PHP
Contents
HTML
Creating a index.html
file.
Create a one file type element for select a file and a button. Triggers AJAX call by click on a button.
<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 id="upload" class="btn btn-info btn-md">Upload</button>
</div>
<div class="form-group">
<span class="message"></span>
</div>
jQuery
Create a FormData
object and append files[0]
to 'file'
key in form_data
.
Call an AJAX request where we pass the
object as data and on successful callback check the response is form_data
1
or not and show message
<script type="text/javascript">
$('#upload').on('click', function(e) {
e.preventDefault();
var file = $('#file-upload').prop('files')[0]; //get file by id
var form_data = new FormData();
form_data.append('file', file); // append file data
$.ajax({
url: 'ajaxfile.php', // <-- point to server-side PHP script
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
if (response==1) {
$('.message').text('file uploaded');
}else if(response==2){
$('.message').text('file not upload');
}else{
$('.message').text('Please select Valid file extensions');
}
}
});
});
</script>
PHP
Create an ajaxfile.php
file and upload
folder to store files.
Read file extension and Initialized valid$valid_extensions
Array.
Check if upload file extension exists in $valid_extensions
Array or not. If exists then upload a file.
Return $response
variable.
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();
}
Good post. I learn something totally new and challenging on blogs I stumbleupon every day. It will always be useful to read content from other writers and use something from other web sites.