JQuery AJAX image upload with form data in PHP
In this blog I will show you that how we can upload an image using jQuery, AJAX, MySql and PHP. We can also upload an image without AJAX and jQuery, but if we want to upload an image or file without reload the page then we have to use AJAX and jQuery. Use below code to upload an image using AJAX with PHP:
ajax.php
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#buttin_upload').on('click', function() {
var file_data = $('#image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output);
}
});
$('#image').val('');
});
});
</script>
<h3> Upload Photo : </h3>
<input type="file" id="image" name='file'><br><br>
<input id="buttin_upload" type="button" value="Submit">
upload.php
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
I've created above 2 files in C drive xampp=> htdocs/learn/ on my local. In learn directory create 1 more directory `uploads`, where uploaded images will store
After that Open this URL http://localhost/learn/ajax.php
In this blog I will show you that how we can upload an image using jQuery, AJAX, MySql and PHP. We can also upload an image without AJAX and jQuery, but if we want to upload an image or file without reload the page then we have to use AJAX and jQuery. Use below code to upload an image using AJAX with PHP:
ajax.php
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#buttin_upload').on('click', function() {
var file_data = $('#image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output);
}
});
$('#image').val('');
});
});
</script>
<h3> Upload Photo : </h3>
<input type="file" id="image" name='file'><br><br>
<input id="buttin_upload" type="button" value="Submit">
upload.php
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
I've created above 2 files in C drive xampp=> htdocs/learn/ on my local. In learn directory create 1 more directory `uploads`, where uploaded images will store
After that Open this URL http://localhost/learn/ajax.php
Latest Comments
Sam
17 Apr 2021hi
24 Mar 2023