Ajax Image Upload Using jQuery, PHP and MySQL
Ajax image upload using jQuey and PHP will give nice user experience than HTML form posting. In this post we are going to see how to upload an image using ajax form posting.
Please refer following tutorial in this series ajax multiple image upload with resize using jQuery and PHP. Here is the link
Refer latest tutorial on ajax image upload
Drag and Drop File Upload jQuery PHP Ajax HTML5 MySQL and Bootstrap
Step 1:
Create html form with input element of file type. Here HTML form source.
<form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post" action="ajax.php"> <div class="form-group"> <p>Please Choose Image: </p> <input class='file' type="file" class="form-control" name="images" id="images" placeholder="Please choose your image"> <span class="help-block"></span> </div> <div id="loader" style="display: none;"> Please wait image uploading to server.... </div> <input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/> </form>
Step2 :
Now add the following two jquery files in your html file.
<script src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.form.min.js"></script>
Step3:
Here jQuery script which is going to handle ajax Form submission. When user selects an image and submits a Form, these following script will checks that image is an valid image. Once that validation is success then jquery.form.js library submit the form using jQuery Ajax.
(function() { $('form').ajaxForm({ beforeSubmit: function() { count = 0; val = $.trim( $('#images').val() ); if( val == '' ){ count= 1; $( "#images" ).next('span').html( "Please select your images" ); } if(count == 0){ for (var i = 0; i < $('#images').get(0).files.length; ++i) { img = $('#images').get(0).files[i].name; var extension = img.split('.').pop().toUpperCase(); if(extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){ count= count+ 1 } } if( count> 0) $( "#images" ).next('span').html( "Please select valid images" ); } if( count> 0){ return false; } else { $( "#images" ).next('span').html( "" ); } }, beforeSend:function(){ $('#loader').show(); $('#image_upload').hide(); }, success: function(msg) { }, complete: function(xhr) { $('#loader').hide(); $('#image_upload').show(); $('#images').val(''); $('#error_div').html(''); result = xhr.responseText; result = $.parseJSON(result); base_path = $('#base_path').val(); if( result.success ){ name = base_path+'images/'+result.success; html = ''; html+= '<image src="'+name+'">'; $('#uploaded_images #success_div').append( html ); } else if( result.error ){ error = result.error html = ''; html+='<p>'+error+'</p>'; $('#uploaded_images #error_div').append( html ); } $('#error_div').delay(5000).fadeOut('slow'); } }); })();
Step 4:
Final PHP part, which gets the submitted image and checks image size as well image format. Once image size and image format validation success, the PHP script uploads that image to the server.
$data = array(); if( isset( $_POST['image_upload'] ) && !empty( $_FILES['images'] )){ $image = $_FILES['images']; $allowedExts = array("gif", "jpeg", "jpg", "png"); if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } //create directory if not exists if (!file_exists('images')) { mkdir('images', 0777, true); } $image_name = $image['name']; //get image extension $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION)); //assign unique name to image $name = time().'.'.$ext; //$name = $image_name; //image size calcuation in KB $image_size = $image["size"] / 1024; $image_flag = true; //max image size $max_size = 512; if( in_array($ext, $allowedExts) && $image_size < $max_size ){ $image_flag = true; } else { $image_flag = false; $data['error'] = 'Maybe '.$image_name. ' exceeds max '.$max_size.' KB size or incorrect file extension'; } if( $image["error"] > 0 ){ $image_flag = false; $data['error'] = ''; $data['error'].= '<br/> '.$image_name.' Image contains error - Error Code : '.$image["error"]; } if($image_flag){ move_uploaded_file($image["tmp_name"], "images/".$name); $src = "images/".$name; $dist = "images/thumbnail_".$name; $data['success'] = $thumbnail = 'thumbnail_'.$name; thumbnail($src, $dist, 200); $sql="INSERT INTO images (`id`, `original_image`, `thumbnail_image`, `ip_address`) VALUES (NULL, '$name', '$thumbnail', '$ip');"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } } mysqli_close($con); echo json_encode($data); } else { $data[] = 'No Image Selected..'; }
Please refer uplaod image error codes – IMAGE ERROR CODE.
Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts
If you want any of my script need to be customized according to your business requirement,
Please feel free to contact me [at] muni2explore[at]gmail.com
Note: But it will be charged based on your customization requirement