Gaurav Mishra
Gaurav Mishra

Reputation: 125

How to show a div till a XHR request completes

I have created a tic-tac-toe game in php. I have created the following code to display the grid & send request to the php-

<html>
<head>
<script type="text/javascript">
function showData(str)
{
    if(str==""){
        document.getElementById("showData").innerHTML="";
    }
    if(window.XMLHttpRequest){
        //code for IE7+, Firefox, Chreom, 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("showData").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","tttoe?move="+str,true);
    xmlhttp.send();
}
</script>
</head>
<body>
<center>
<div id="showData">
<table border="1" cellpadding="1" cellspacing="1">
    <tr>
        <td>&nbsp;<input type="button" class="button1" name="move" value="1" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="2" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="3" onClick="showData(this.value)" />&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;<input type="button" class="button1" name="move" value="4" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="5" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="6" onClick="showData(this.value)" />&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;<input type="button" class="button1" name="move" value="7" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="8" onClick="showData(this.value)" />&nbsp;</td>

        <td>&nbsp;<input type="button" class="button1" name="move" value="9" onClick="showData(this.value)" />&nbsp;</td>
    </tr>
</table>
</div>
</center>
</body>
</html>

Is there a way so that I can show a text (Processing.....) Till the request completes?

Upvotes: 0

Views: 102

Answers (1)

Leri
Leri

Reputation: 12535

You can add div with id status in your html and in your js:

document.getElementById('status').innerHTML = 'processing';

at the beginning of your function and

document.getElementById('status').innerHTML = 'whatever you want';

after

if(xmlhttp.readyState==4 && xmlhttp.status==200){

Upvotes: 2

Related Questions