Image upload without refresh page in php and jquery
This is a simple php and jquery based image upload script to upload image without page refresh
Lets see how this works
- Create a html page with some jquery script
index.html
<html> <head> <title>Image upload without refresh page</title> </head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.js"></script> <script type="text/javascript" > $(document).ready(function() { $(document).on('change', '#photoimg', function(){ $("#preview").html(''); $("#preview").html('<img src="loader.gif" alt="Uploading...."/>'); $("#imageform").ajaxForm({ target: '#preview' }).submit(); }); }); </script> <style> body { font-family:arial; } .preview { width:200px; border:solid 1px #dedede; padding:10px; } #preview { color:#cc0000; font-size:12px } </style> <body> <div style="width:600px"> <form id="imageform" method="post" enctype="multipart/form-data" action='upload.php'> Upload your image <input type="file" name="photoimg" id="photoimg" /> <br> <input type="text" id='tt' name='tt'> </form> <div id='preview'> </div> </div> </body> </html> |
- Create upload.php file and copy and paste below in upload.php file.
upload.php
<?php $path = "img/"; $valid_formats = array(".jpg", ".png", ".gif", ".bmp"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { //echo $name = $_POST['tt']; $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($name)) { $fileExt = substr(strrchr($name, '.'), 0); if(in_array($fileExt,$valid_formats)) { if($size<(1024*1024)) { $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if(move_uploaded_file($tmp, $path.$actual_image_name)) { echo "<img src='img/".$actual_image_name."' class='preview'>"; } else echo "failed"; } else echo "Image file size max 1 MB"; } else echo "Invalid file format.."; } else echo "Please select image..!"; exit; } ?> |