On so many web sites when ajax is being used to update part of the page sometimes we see 404 server response page which is the ugly part. This is due to lack of proper knowledge of developers on Ajax.
Solution:-
The ideal solution would be to do nothing if the response from the server is not ok. To do this we should check the Ajax request status. if the Ajax request status is 200 that mean the server response is proper, if not then there is a problem. So do nothing when there is a problem.
The following is the code for complete Ajax call:-
function getHTTPObject() {
if (typeof XMLHttpRequest != 'undefined') {
return new XMLHttpRequest();
}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
return false;
}
<script type="text/javascript">
function getSearchStudents(){
document.getElementById("noStudent").style.visibility = "hidden";
var userString=document.getElementById("userString").value;
var http=getHTTPObject();
http.open("GET", "searchStudent.do?userString="+userString, true);
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
document.getElementById("container").innerHTML=http.responseText;
if(http.responseText=="")
document.getElementById("noStudent").style.visibility = "visible";
if(http.responseText.length==2)
document.getElementById("noStudent").style.visibility = "visible";
}
}
http.send("");
}
</script>
One good thing that developer needs to know is the states of the Ajax request. There are four states. The "readyState" property can hold four values that is 0,1,2,3,4.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
No comments:
Post a Comment