Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display loading image while ajax fetches file content

Tags:

ajax

i am new to ajax and read some tuts to make a lil script which has multiple buttons and on click each will load a php file in a specific div. for that im using this

function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
   document.getElementById("1").innerHTML=xmlhttp.responseText;
        }
  }
xmlhttp.open("GET","feedchck.php",true);
xmlhttp.send();
}  

Action Button :

<button type="button" onclick="loadXMLDoc();">Request</button>
<div id="1">asdf</div>

I made it to this part and on click the php file is loading perfectly. but coz it takes time to process it shows blank area. so is it possible to show a loading image or text while it processes and after completion it will hide the image and display file content?
Help is appreciated :}
cheers

like image 310
Ayaz Malik Avatar asked May 18 '12 04:05

Ayaz Malik


1 Answers

<button type="button" onclick="loadXMLDoc();">Request</button>
<!--An empty tag - this be the loading image-->
<span id="loading"></span>
<div id="1">asdf</div>

<script>
function loadXMLDoc() {
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("loading").innerHTML = ''; // Hide the image after the response from the server
            document.getElementById("1").innerHTML = xmlhttp.responseText;
        }
    }
    document.getElementById("loading").innerHTML = '<img src="../loading.gif" />'; // Set here the image before sending request
    xmlhttp.open("GET", "feedchck.php", true);
    xmlhttp.send();
}
</script>
like image 127
sathish Avatar answered Dec 01 '22 11:12

sathish