I use this AJAX code:
<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) {
try{
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
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "file.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
How to indicate AJAX loading?
Common scenario is to show animated gif image or change mouse cursor on start of ajax request and at end.
Gif is much simpler. Something like (I am using JQuery Syntax): For start:
$("#progressIndicator").show();
In your onreadystatechange handler
$("#progressIndicator").hide();
If your using JQuery you can do something like this:
$("#progressIndicator").show();
var age = $('#age')[0].value;
var wpm = $('#wpm')[0].value;
var sex = $('#sex')[0].value;
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
$.get("file.php" + queryString, function (data) {
$("ajaxDiv").html(data);
$("#progressIndicator").hide();
})
you can see more about the JQuery get method here
You can bind the showing/hiding globally in your app (or just in some part of it) with the following events:
$(document).on({
ajaxStart: function () { $body.addClass("loading"); },
ajaxStop: function () { $body.removeClass("loading"); }
});
And then you define the class loading:
/* Start by setting display:none to make this hidden.
Then we position it in relation to the viewport window
with position:fixed. Width, height, top and left speak
for themselves. Background we set to 80% white with
our animation centered, and no-repeating */
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, .8 ) url('../Images/Loader.gif') 50% 50% no-repeat;
}
/* When the body has the loading class, we turn the scrollbar off with overflow:hidden */
body.loading {
overflow: hidden;
}
/* Anytime the body has the loading class, our modal element will be visible */
body.loading .modal {
display: block;
}
In this way you don't need to manage the loading effect for every ajax call and you can maintain a consistent style through the entire application.