Seach

how to upload and display image before submiting using php and jquery

main.php
<head>
    <link href="css/style.css" type="text/css" rel="stylesheet"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<form method="post" enctype="multipart/form-data" action="upload.php" id="form1">
    <div id="imagePreview">
       
    </div>
<input id="uploadFile" type="file" name="image" class="img" />
<input type="submit" name="save" id="save">
</form>
<script type="text/javascript">
$(document).ready(function(){
    $("#uploadFile").on("change", function()
    {
        var files = !!this.files ? this.files : [];
         // no file selected, or no FileReader support

        // only image file
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(files[0]); // read the local file
          reader.onloadend = function()
            { // set image data as background of div
                $("#imagePreview").css("background-image", "url("+this.result+")");
            }
       
    });
    $("#form1").on("submit",function (e)
    {
        e.preventDefault();
        $.ajax(
                {
                    url:"upload.php",
                    type:"post",
                    cache: false,
                    contentType: false,
                    processData: false,
                    data:new FormData(this),
                    success: function (data, textStatus, jqXHR) {
                        alert(data);
                    }
                });
    }
                );
  
   
});
</script>

upload.php
<?php
if(is_array($_FILES))
{
    $destination="image/".$_FILES["image"]["name"];
    $source=$_FILES["image"]["tmp_name"];
   if( move_uploaded_file($source, $destination))
   {
       echo "image uploaded";
   }
   
}

?>

style.css
#imagePreview
{
width: 180px;
    height: 180px;
    background-position: center center;
    background-size: cover;
    -webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
    display: inline-block;
}