Tuesday, 11 February 2014

Upload and display an image without a page refresh using Javascript and PHP

Upload and display an image Here Iam explain about how to upload an image without a page refresh using an iframe and some javascript.
Bunch of jquery plugins that do this, but you’ll see here that there is nothing really complicated about it and it can easily be achieved with a couple of javascript lines.

The trick to avoid this full page refresh is to use a ‘target’ attribute on the form and have it point to an iframe. As the submit button is clicked, the browser will load up the response in the targeted iframe without refreshing the whole page.

  function image_upload()
  document.getElementById('status').innerHTML='<img src="images/loading.gif" width="140px;" height="140px;"  style="margin-top:20px;margin-left:20px;display:inline;">';
  document.submitform.action ="upload.php";
  document.submitform.target = "showimage";

  <form name="submitform" id="submitform" method="post" enctype='multipart/form-data' action="">
  <input type="hidden" name="image_name" id="image_name" >
  <div id="status"><img src="images/default.jpeg" alt="previewimage" id="default_image"  width="140px;" height="140px;" style="border:1px solid; background: #fff;padding: 1px;"/>
         </div><br />

 Choose Image :<input id="yourimage" name="yourimage" type="file" onchange="return image_upload(this);" />
 <iframe name="showimage" style="display:none"></iframe>
    $imagename_1 = $_FILES['yourimage']['name'];
  $imagename_2 = strtolower($imagename_1) ;
  $exts = split("[/\\.]", $imagename_2) ;
  $n = count($exts)-1;
  $ext = strtolower($exts[$n]);
  $imgNewName = date("MDYHis").".".$ext;
  $imagepath = 'images/'.$imgNewName;    
 if (move_uploaded_file($_FILES['yourimage']['tmp_name'],$imagepath) ) {
   echo "<script>parent.document.getElementById('status').innerHTML='<img src=\"".$imagepath."\"  width=\"140px;\" height=\"140px;\"  style=\"border: 1px solid ;background:#fff;\" id=\"default_image\" ><br>';</script>";

echo "<script>parent.document.getElementById('image_name').value='".$imgNewName."';</script>";
 } else {
                echo "error";

No comments:

Post a Comment