Sunday, November 8, 2015

Image Upload PHP JQuery Ajax

JQuery
We Want to upload an image without refresh a page and that can possible by Ajax.Here we use the JQuery and Ajax to upload an image.
In this example user select an image and click on Upload button and the image displayed without refresh a page.


Ajax Image Upload JQuery PHP

HTML FORM 

<form name="image_form" id="image_form" action="" enctype="multipart/form-data" method="post" >
<input type="file" class="textbox" id="image" name="image" required>
<input type="submit" name="submit" value="Upload" id="upload">
</form>

JQUERY SCRIPT 


<script type="text/javascript"> 
$(document).ready(function (e) {
    $("#image_form").on('submit',(function(e) {
        e.preventDefault();
        $.ajax({
            url:"upload.php",
            type: "POST",
            data:  new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
            $("#display=").html(data);
            },
              error: function()
            {
            }            
       });
    }));
});
</script>

PHP SCRIPT 

<?php
    if(is_array($_FILES))
    {
        $target_dir = "images/";
        $file_name=$_FILES['image']['name'];
        $full_name = explode('.',$file_name);
        $file_name = time().'.'.$full_name[1]; //Replace Image name with Time
        $target_file = $target_dir . basename($file_name);
        $targetPath = "images/".$_FILES['image']['name'];
        if(move_uploaded_file($_FILES["image"]["tmp_name"],$target_file))
        {
?>
<img src="<?php echo $target_file; ?>" width="200px" height="200px" />
<?php
}
}
?>

CLICK HERE FOR DOWNLOAD COMPLETE CODE... 

0 comments:

Post a Comment