Saturday, April 7, 2012

Ajax Image Upload without Refreshing Page using Jquery

0

This is simple markup of image uploading without page refresh and submit other form fields using jquery.form.js

Step 1. Javascript:

<script src="http://glll.googlecode.com/files/jquery.form.js" type="text/javascript">
</script>
<script src="http://malsup.github.io/jquery.form.js" type="text/javascript">
</script>

<script type="text/javascript">
$(document).ready(function() { 
$('#BtnSubmit').live('click', function(){ 
$("#result").html('');
$("#result").html('loading....');
$("#frm").ajaxForm({target: '#result'}).submit();
});
}); 
</script>

Step 2. html:

<div style="width:600px">

<form id="frm" method="post" enctype="multipart/form-data" action='image_upload.php'>
<table cellpadding="2" cellspacing="2" border="1" >
<tr><td>Username:</td><td><input type="text" name="username" id="username" /></td></tr>
<tr><td>Password:</td><td><input type="password" name="pswrd" id="pswrd" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="email" id="email" /></td></tr>
<tr><td>Upload your image:</td><td> <input type="file" name="file" id="file" /></td></tr>
<tr><td colspan="2"><input type="button" id="BtnSubmit" name="BtnSubmit" value="submit" ></td></tr>
</table>
</form>

<div id='result'>
</div>
</div>

Step 3. php:

<?php
$dir = "photos/";

$valid_ext = array("image/jpg","image/jpeg", "image/png", "image/gif", "image/bmp");
if(isset($_POST) &&  $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
if($name)
{
$mime=getimagesize($_FILES['file']['tmp_name']);


if(in_array($mime['mime'],$valid_ext))////validating the image format is valid
{
if($size<(1024*1024*5))//////////limit to 5MB size////
{
$ext=explode('.',$name);
$image_name = time().'.'.$ext[1];
$tmp = $_FILES['file']['tmp_name'];
if(move_uploaded_file($tmp, $dir.$image_name))
{
//mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");

echo "<img src='".$dir.$image_name."'>";
}
else
echo "failed";
}
else
echo "Image file size max 5 MB";     
}
else
echo "Invalid file format.."; 
}

else
echo "Please select image..!";

exit;
}
?>

No comments :

Post a Comment