Subham Sb Subham Sb - 1 year ago 63
Ajax Question

Where to put a loading icon in this ajax form please anyone tell me?

My code is like this i took it from a tutorial website dont remember where please tell me where to put a loading icon in this huge junk of code i dont understand.
Please show me an example via jsfiddle or anywhere else.

<script language = "javascript" type = "text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!

try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;

// Create a function that will receive data
// sent from the server and will update
// div section in the same page.

ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;

// Now get the value from user and pass it to
// server script.

var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;

queryString += "&wpm=" + wpm + "&sex=" + sex;"GET", "ajax-example.php" + queryString, true);

<form name = 'myForm'>
Max Age: <input type = 'text' id = 'age' /> <br />
Max WPM: <input type = 'text' id = 'wpm' />
<br />

Sex: <select id = 'sex'>
<option value = "m">m</option>
<option value = "f">f</option>

<input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>


<div id = 'ajaxDiv'>Your result will display here</div>

Answer Source

First, check this out for more info on ready states.

I'd put a loading just before"GET", "ajax-example.php" + queryString, true); and remove it on if (xmlhttp.readyState==4.


So add HTML where you'd like the loading icon to appear: <span id="loading"></span>


Then just before insert loading image:

document.getElementById("loading").innerHTML = '<img src="loading.gif" />';


And inside if (xmlhttp.readyState == 4 put:

document.getElementById("loading").innerHTML = '';

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download