In this tutorial we have a simple script which will Upload an Image using jQuery Ajax with PHP, we have simple file uploading tutorial on this blog but how about using ajax, it is very simple to upload an image to the server via jQuery ajax() without refreshing the whole page, once an image was uploaded it will be viewed on the same page. PHP code was used at the back-end which will select and upload an image and the uploading process will be done by ajax() method, let's see ajax php image upload example.
there are only 3 files we need for this tutorial, simple HTML form to accept valid image file, php file to upload selected image to the server side and javascript code to upload image easily without reloading page and to view the uploaded file into the particular div.
that's it, how it becomes easy to upload an image to the server via ajax code, feel free to contact me regarding this tutorial, hope you like it.
there are only 3 files we need for this tutorial, simple HTML form to accept valid image file, php file to upload selected image to the server side and javascript code to upload image easily without reloading page and to view the uploaded file into the particular div.
index.php
simple file contains only html form to accept image file to upload and send the request to the PHP file called "ajaxupload.php" via ajax() method.
<!doctype html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Easy Ajax Image Upload with jQuery and PHP - codingcage.com</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
<h1><a href="">Easy Ajax Image Upload with jQuery</a></h1>
<hr>
<div id="preview"><img src="no-image.jpg" /></div>
<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
<div id="err"></div>
<hr>
<p><a href="http://www.codingcage.com" target="_blank">www.codingcage.com</a></p>
</div>
</body>
</html>
ajaxupload.php
this file contains only PHP code which will upload an image to the directory "uploads/" via ajax, here i have given the validation for the image and it will upload only valid extension images.<?php
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
}
else
{
echo 'invalid file';
}
}
?>
script.js
Simple jQuery/JavaScript code to upload and view image without page refresh. using $.ajax() method an image file wil be send to the "ajaxupload.php" file and file will be uploaded and viewed at the same time.$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
that's it, how it becomes easy to upload an image to the server via ajax code, feel free to contact me regarding this tutorial, hope you like it.
A script for popup login in php with mysql please. Help will be appreciated
ReplyDeleteHello Himanshu, i will post login/signup popup tutorial soon ...
Deletei have got one. Will give as a code of thanks please tell me how could i send it to you??
DeleteHi Himanshu, you can mail me ...
DeleteHello ! Is it possible to have same script with insert record in Mysql Database ?
ReplyDeleteCETMOI DENIS, yes, it is possible.
DeletePut the SQL instructions right after the "echo" on the script
if(move_uploaded_file($tmp,$path))
{
echo "your image";
//Here goes your sql instructions - if the image is successfully uploaded to the folder, //you should be able to insert data on mysql
}
Hope it helps!
thanks for the tutorials, I learned a lot
ReplyDeleteyou're welcome, jose, keep visiting :)
DeleteAmazing tutorial, Can't thank you enough!
ReplyDeletethanks yudi :)
DeleteThanks for sharing great information
ReplyDeleteyou're welcome , cinchu :)
Deleteyou're welcome , cinchu :)
DeleteHow do I preview the image before I upload it?
ReplyDeletethis php script is really nice and awesome and it is really it is best blog thanks
ReplyDeletephp Training in Chennai
Hi, Pradeep, thanks for sharing this code..
ReplyDeleteI use this code to update image file.. it's working... but when I implemented this code to update image file to database, it only sent null to image coloum... how to fix it?
Gracias!!!
ReplyDeleteI always like to reference tutorials like this. Really well done~
ReplyDelete--
Sam Smith
Technology Evangelist and Aspiring Chef
Large file transfers made easy.
www.innorix.com/en/DS
Thanks for yout tutorial.
ReplyDeleteGreat post. Keep sharing such a useful post.
ReplyDeleteDigital marketing training in chennai
Thaks for sharing the nice tutorial.
ReplyDeleteyou're welcome, Aburehan :)
DeleteHello ! Is it possible to have same script with insert record in Mysql Database ?
ReplyDeleteGood Job on this post. Thank you for taking the time to help others.
ReplyDeleteTHANK YOU...!!!
Wow gracias por el post esta calidad lo he mejorado haber como hago para subirlo y compartir de igual que ustedes...!!
ReplyDeleteThank u very much for great image upload script...using ajax
ReplyDeleteWhat if I have 7 different inputs how do I store it in the database? Please help thanks.
ReplyDeleteWhat if I had 7 different image inputs how do I store the BLOB in database? Please help me I'm kinda stuck in my current situation. Thanks.
ReplyDeletePretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
ReplyDeleteRegards,
PHP Training in Chennai | Webdesigning Training in Chennai
Thank yoou for posting useful post.Request to visit
ReplyDeleteBest dotnet training in chennai
I love your work! It is simple,
ReplyDeleteyet effective. You have inspired me to create organized worksheets just like yours.
Your students are lucky to have you! Thanks for all the freebies!...best regards....best regards.
sap hana online training
Wonderful guide. This is really informative and effective post. Thanks for the shearing and keep update more.
ReplyDeleteInternet Marketing Courses in Chennai