Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include loading gif while file upload and insert to database is in progress

I have to load a file into a temporary location first before reading it and inserting it into a database. But how can I include a loading gif while its doing all of these, can someone please show me? -Thanks

<input type="file" name="myfile">
<input type="submit"  id = "upload" value="Upload">    
<div id= "loading_gif">
</div>


$(document).ready(function () {
$("#upload").click(function () {     

    $.ajax({
        type: "POST",
        url: "upload.php",
        enctype: 'multipart/form-data',
        data: {
            file: myfile
        },
        success: function () {
            alert("Data has been Uploaded: ");
          }
       });
     });
  });



<?php
$temp_location = "tmp/";

if(isset($_FILES["myfile"]))
{    
  if ($_FILES["myfile"]["error"] > 0)
  {
     echo "File loading error! ";
  }
  else
  {        
    move_uploaded_file($_FILES["myfile"]["tmp_name"],
    $temp_location. $_FILES["myfile"]       ["name"]);

    //read myfile and insert data into database

    echo "File uploaded into database";
   } 
  }
?>
like image 515
ArchieTiger Avatar asked Oct 22 '13 18:10

ArchieTiger


1 Answers

I assume you have an image loading.gif. put it into img tag and set it's id to 'loading', and then make it invisible.

<img id='loading' src='loading.gif' style='visibility: hidden;'>

You have to create javascript functions to show and hide the loading image. Here's the script:

<script>
function showLoading(){
document.getElementById("loading").style = "visibility: visible";
}
function hideLoading(){
document.getElementById("loading").style = "visibility: hidden";
}
</script>

To show the loading image when you are uploading, call the showLoading() function jus before the ajax call, and then hide it when you are done uploading with hideLoading() function.
Here's the implementation :

$("#upload").click(function () {     
    //call show loading function here
    showLoading();
    $.ajax({
        type: "POST",
        url: "upload.php",
        enctype: 'multipart/form-data',
        data: {
            file: myfile
        },
        success: function () {
            //call hide function here
            hideLoading();
            alert("Data has been Uploaded: ");
        },
        error  : function (a) {//if an error occurs
            hideLoading();
            alert("An error occured while uploading data.\n error code : "+a.statusText);
        }
    });
});

And I know you know where you have to put the jquery script inthe document. :D

like image 179
Oki Erie Rinaldi Avatar answered Oct 19 '22 06:10

Oki Erie Rinaldi