Is It Possible to Upload Images With Ajax
Ajax Image Upload using PHP and jQuery
Updated on July one, 2020
past Neeraj Agarwal
In this blog post we accept covered one of the topic of ajax i.eastward. to upload images using Ajax and phpwithout page refresh.
Brusk Description :
In this process the image is selected first and previewed before storing it in to any location . Then using jQuery Ajax, it is ship to php script on submit button effect.
PHP script stores the image in a divers location and returns the bulletin of the success and failure of the procedure.
Here we accept applied some validations on the selected file, to check information technology whether it is an prototype file (jpg, jpeg or png ) or any other file type.
Upload File size allowed is 100 Kb.
Following steps are pointed nether this process :
1. Include jQuery library.
2. HTML page with upload field.
3. jQuery Ajax code.
3. PHP script to shop image.
Ajax Code :
$.ajax({ url: "ajax_php_file.php", // Url to which the asking is send blazon: "Post", // Blazon of request to be send, called every bit method information: new FormData(this), // Information sent to server, a gear up of cardinal/value pairs (i.e. course fields and values) contentType: fake, // The content blazon used when sending data to the server. enshroud: false, // To unable request pages to be buried processData:false, // To send DOMDocument or not candy data file it is set up to false success: role(data) // A office to be called if asking succeeds { $('#loading').hide(); $("#message").html(data); } });
PHP lawmaking used to shop the image :
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable $targetPath = "upload/".$_FILES['file']['proper noun']; // Target path where file is to be stored move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
Beneath is our complete code with the live demo and download option
HTML page containing file upload field.
HTML file : ajax_upload_image_main.php
<html> <head> <championship>Ajax Image Upload Using PHP and jQuery</title> <link rel="stylesheet" href="style.css" /> <link href='http://fonts.googleapis.com/css?family unit=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' blazon='text/css'> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="script.js"></script> </head> <torso> <div class="main"> <h1>Ajax Paradigm Upload</h1><br/> <hour> <form id="uploadimage" action="" method="mail service" enctype="multipart/form-data"> <div id="image_preview"><img id="previewing" src="noimage.png" /></div> <hr id="line"> <div id="selectImage"> <label>Select Your Image</label><br/> <input blazon="file" name="file" id="file" required /> <input type="submit" value="Upload" class="submit" /> </div> </form> </div> <h4 id='loading' >loading..</h4> <div id="message"></div> </body> </html>
Complete jQuery Lawmaking : script.js
$(document).set up(function (e) { $("#uploadimage").on('submit',(function(due east) { due east.preventDefault(); $("#message").empty(); $('#loading').show(); $.ajax({ url: "ajax_php_file.php", // Url to which the request is send type: "POST", // Type of request to be ship, called equally method information: new FormData(this), // Data sent to server, a set of key/value pairs (i.east. course fields and values) contentType: fake, // The content type used when sending data to the server. cache: simulated, // To unable request pages to exist buried processData:false, // To send DOMDocument or non processed information file it is set to false success: office(information) // A function to exist called if request succeeds { $('#loading').hibernate(); $("#message").html(data); } }); })); // Function to preview image after validation $(office() { $("#file").change(function() { $("#message").empty(); // To remove the previous mistake bulletin var file = this.files[0]; var imagefile = file.blazon; var match= ["image/jpeg","prototype/png","image/jpg"]; if(!((imagefile==match[0]) || (imagefile==friction match[1]) || (imagefile==match[2]))) { $('#previewing').attr('src','noimage.png'); $("#message").html("<p id='mistake'>Please Select A valid Epitome File</p>"+"<h4>Note</h4>"+"<bridge id='error_message'>Only jpeg, jpg and png Images type allowed</bridge>"); return fake; } else { var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files[0]); } }); }); function imageIsLoaded(e) { $("#file").css("color","greenish"); $('#image_preview').css("display", "block"); $('#previewing').attr('src', due east.target.result); $('#previewing').attr('width', '250px'); $('#previewing').attr('height', '230px'); }; });
PHP Script : ajax_php_file.php
<?php if(isset($_FILES["file"]["type"])) { $validextensions = array("jpeg", "jpg", "png"); $temporary = explode(".", $_FILES["file"]["name"]); $file_extension = stop($temporary); if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "epitome/jpg") || ($_FILES["file"]["type"] == "image/jpeg") ) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["fault"] . "<br/><br/>"; } else { if (file_exists("upload/" . $_FILES["file"]["name"])) { repeat $_FILES["file"]["proper name"] . " <span id='invalid'><b>already exists.</b></span> "; } else { $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable $targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file echo "<span id='success'>Paradigm Uploaded Successfully...!!</span><br/>"; echo "<br/><b>File Proper name:</b> " . $_FILES["file"]["name"] . "<br>"; echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>"; echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>"; } } } else { echo "<span id='invalid'>***Invalid file Size or Type***<span>"; } } ?>
CSS code : mode.css
body { font-family unit: 'Roboto Condensed', sans-serif; } h1 { text-align: centre; background-color: #FEFFED; elevation: 70px; color: rgb(95, 89, 89); margin: 0 0 -29px 0; padding-top: 14px; border-radius: 10px 10px 0 0; font-size: 35px; } .master { position: accented; top: 50px; left: 20%; width: 450px; height:530px; border: 2px solid gray; border-radius: 10px; } .principal label{ colour: rgba(0, 0, 0, 0.71); margin-left: 60px; } #image_preview{ position: absolute; font-size: 30px; superlative: 100px; left: 100px; width: 250px; height: 230px; text-align: centre; line-height: 180px; font-weight: bold; colour: #C0C0C0; background-color: #FFFFFF; overflow: automobile; } #selectImage{ padding: 19px 21px 14px 15px; position: absolute; bottom: 0px; width: 414px; background-color: #FEFFED; border-radius: 10px; } .submit{ font-size: 16px; background: linear-slope(#ffbc00 5%, #ffdd7f 100%); border: 1px solid #e5a900; colour: #4E4D4B; font-weight: assuming; cursor: pointer; width: 300px; border-radius: 5px; padding: 10px 0; outline: none; margin-pinnacle: 20px; margin-left: fifteen%; } .submit:hover{ background: linear-gradient(#ffdd7f 5%, #ffbc00 100%); } #file { color: red; padding: 5px; border: 5px solid #8BF1B0; groundwork-color: #8BF1B0; margin-elevation: 10px; border-radius: 5px; box-shadow: 0 0 15px #626F7E; margin-left: 15%; width: 72%; } #message{ position:accented; summit:120px; left:815px; } #success { color:greenish; } #invalid { color:red; } #line { margin-top: 274px; } #error { color:cerise; } #error_message { colour:blueish; } #loading { display:none; position:absolute; top:50px; left:850px; font-size:25px; }
Determination :
In this blog postal service we have covered a basic topic of ajax of uploading paradigm using php with applied validations in it. Hope this might have worked for yous to understand the ajax property. Keep reading our other blog posts for more coding tricks.
41 Replies to "Ajax Epitome Upload using PHP and jQuery"
Source: https://www.formget.com/ajax-image-upload-php/
good
Reply
Hello,
Information technology seems to exist great solution for other browsers but demo is non working on IE8. Will happy if you provide whatever solution to resolve this cause. Once again its a good solution 🙂
Respond
That's really helpful! Thanks a lot!
Reply
Thanks for this tutorial i.it is a very useful to me
Reply
Really wonder for what you provide this code. It solve my headache problem
Reply
swell mail and interesting feedback from others. Cheers for sharing, how to rotate the image since it is uploaded right words.
thanks
Answer
explain php coding for $targetpath and $sourcepath .where they are storing and where it is placed
Reply
Excuse me, can I know how to add other variable every bit information to exist postal service with file information?
thanks so much for the code, hope you can help me with this too..
Answer
I think the file-data is seperated from the post-information. The file-data is in $_FILES, the post-data in $_POST. You can handle both information with different functions.
Reply
Thank you! This is a great help! God bless
Reply
how-do-you-do there, is it possible to have the class car submit when an image is selected? ive tried putting the ajax code in the onchange for the file field but its not working, besides tin can u run this without the grade? ie just standalone js?
Reply
Good tutorial! Really helped me out. Tin can you delight tell me how to brand the selected paradigm [preview and upload name] become back to normal subsequently the image is uploaded? Eagerly waiting for your reply. Give thanks You.
Reply
Its good.very useful code
Reply
Bang-up tutorial and very useful. PERFECT 🙂 solve my problem
Reply
Thanks information technology helped me a lot, crawly tutorial, Please upload one more tutorial regarding uploade images using ajax and progress bar
Reply
Cheers
Respond
Thanks. Was actually helpful.
Reply
Hi,
The epitome is uploading for only one time ,, for the 2nd or more times is not working ..please cheque
Thanks
mahesh
Reply
Thank you VERY MUCH! THIS IS A GREAT AND Error Costless 100% WORKING Instance!
Answer
how i can brand random upload file name ?
i have a idea for php code :
function genRandomString()
{
$length = 5;
$characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ";
$real_string_length = strlen($characters) ;
$string="id";
for ($p = 0; $p < $length; $p++)
{
$string .= $characters[mt_rand(0, $real_string_length-one)];
}
return strtolower($string);
}
Reply
Very nice explanation on AJAX, give thanks y'all very much. Very helpful for me!!
Answer
but how to apply this code ?
when file uploaded ajax relieve file proper noun input box as file type i can non read value of genRandomString()
delight help me.
Answer
jquery relieve value input box as file to subconscious input box you can see my code upload in :
http://bechat.in/signup/
and all code is :
index.php {
sstart();
?>
Sign_Title; ?>
<form method="mail service" action="">
Sign upward
<input name="rname" placeholder="Sign_firstname; ?>" blazon="text">
<input name="rfamily" placeholder="Sign_lastname; ?>" blazon="text">
<input name="remail" placeholder="Sign_Email; ?>" type="postal service">
<input proper name="rusername" placeholder="Sign_UserName; ?>" type="text">
<input proper noun="rpassword" placeholder="Sign_Password; ?>" type="password">
<input name="repeatpassword" placeholder="Sign_PasswordConfig; ?>" blazon="password">
<input type="submit" value="Sign_Login; ?>">
Browse
Login
select("`username`","`user`","`username`='$rusername'");
if(mysql_num_rows($result)>=i)
{
$bool=truthful;
}
if(!pregmach($rusername))
{
$bool=true;
}
if(!pregmach($rpassword))
{
$bool=true;
}
if(!checkemail($remail))
{
$bool=true;
}
if($bool==truthful)
{
echo "Erorr register ..";
}else{
if(empty($imageurl) || $imageurl =="avatar.png"){
$sql->insert("`user`","'$rusername','$rpassword','system','$rname','$rfamily','$remail','avatar.png'","`username`, `password`,`list`,`name`,`family unit`,`email`,`avatar`","");
header("location:../index.php");
}else{
$sql->insert("`user`","'$rusername','$rpassword','system','$rname','$rfamily','$remail','$imageurl'","`username`, `password`,`list`,`name`,`family`,`email`,`avatar`","");
header("location:../index.php");
}
}
}
?>
//End alphabetize.php}
upload.php {
500000) {
repeat '{"status":"mistake"}';
}else{
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../image/profile/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
}
}else{
echo '{"status":"fault"}';
}
}
echo '{"status":"error"}';
leave;
//}
js.js (coffee script file ){
$(office(){
var ul = $('#upload ul');
$('#drop a').click(function(){
// Simulate a click on the file input push button
// to show the file browser dialog
$(this).parent().find('input').click();
});
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
// This element volition take file drag/drib uploading
dropZone: $('#drib'),
// This function is called when a file is added to the queue;
// either via the scan button, or via drag/drop:
add: function (e, data) {
var tpl = $(");
// Append the file name and file size
$("#signup-avatar img").attr("src","../paradigm/profile/"+data.files[0].name);
$("#imageurl").val(data.files[0].name);
tpl.notice('p').text(data.files[0].name)
.append('' + formatFileSize(data.files[0].size) + '');
// Add the HTML to the UL element
information.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.discover('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// and then that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
},
neglect:function(e, information){
// Something has gone wrong!
data.context.addClass('error');
}
});
// Prevent the default activeness when a file is dropped on the window
$(certificate).on('drop dragover', office (e) {
due east.preventDefault();
});
// Helper function that formats the file sizes
function formatFileSize(bytes) {
if (typeof bytes !== 'number') {
render ";
}
if (bytes >= 1000000000) {
render (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= meg) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
}
});
//end js.js
i tin not return result when generated by php function.
Reply
Then good, thanks!
Reply
very useful and good
Respond
Good and overnice tutorial, many tutorial on other site not articulate and not obvious like on this site.
Answer
Mine is non working. am I going to modify the noimage.png? Cheers
Answer
I am getting the following mistake
Notice: Undefined alphabetize: file_1 in C:\wamp\www\site1\test.php on line two
Respond
That is very bully tuto! thanks a lot for the lawmaking :p
Reply
First-class script! Give thanks y'all and then much — it'due south working great both on my dev box and my production server.
Answer
I purchased this parcel and had to set many things for a LAMP setup, and integrate into existing code.
I consider myself higher up amateur (forty+ years in IT, 15 years in web development), nonetheless I cannot figure out when I choose an image to upload, I get "C:\fakepath" as a response in the file name field. Where does that come up from and how can I suppress it and so that just the file proper name shows?
Reply
fakepath is chrome browser default holding. Use this aforementioned code in other browser and the text "fakepath" automatically modify.
Answer
Cheers Man … Awesomeeeeeeeeeeeee :] 😀 😀
Respond
Many thanx, I had always been keeping my file uploads on a separate page, now I can integrate them with my forms.
Reply
Maybe this will assistance somebody else:
To autosubmit the form when the user selects the paradigm add this after 'reader.readAsDataURL(this.files[0]);' : '$("#uploadimage").submit();' without the quotes.
To solve the trouble when you submit the form using prototype "A.jpg" and then you try to submit the form over again using the aforementioned photograph add this to the ajax success function: " $("#file").replaceWith("); " and replace "$("#file").change" with " $(certificate).on('change', '#file', function(){ " .
Hope this will help somebody else.
Reply
Yes
very helpful thank you WingmanImd .
Reply
Sir
skilful script, working
simply 'move_uploaded_file' not working.
file non moves to folders
Answer
Ever make sure the binder you are trying to re-create a file to, already exists. 😉
Reply
look so nice thanks
Answer
hello sir
i have a question if I take upload paradigm and signature image on single upload push button before upload demand to click on check box 1 bank check box for image and one for signature after click on either sig or prototype then prototype save database and display in box signature box in signature paradigm box in box
Sir tin you guide us how can we practise
Thanks
Answer
Hullo ! ! !
I need a 2nd upload for 2 Pictures. Can y'all help me ?
When i duplicate the function and add an new preview fiel information technology'due south doesent work. The Preview of both Buttons displays in 2d preview div
Greets
Malcom
Reply