Forum Moderators: open

Message Too Old, No Replies

Ajax without jQuery

         

ahmed24

11:14 am on Dec 24, 2014 (gmt 0)

10+ Year Member



I've compiled the following code which works at processing my login form using Ajax without jQuery. Just not sure if it's the most efficient way to do it and hoping someone can advise if it can be improved any further.



var xmlhttp;

function loadXMLDoc(url,cfunc) {

if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=cfunc;
xmlhttp.open('POST', url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + document.getElementById("username").value + "&passwd=" + document.getElementById("passwd").value + "&_SESSION=" + document.getElementById("_SESSION").value);

}

function Login() {

loadXMLDoc("/Login.php",function() {
document.getElementById("ErrorBox").style.display = "none";
document.getElementById("SignInButton").value="please wait..";
document.getElementById("SignInButton").setAttribute("disabled","disabled");
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var loginResponse = xmlhttp.responseText;

if (loginResponse == 2) {
window.location="/portal/";
} else if (loginResponse == 3) {
document.getElementById("staffErrorBox").style.display = "block";
document.getElementById("staffErrorBox").innerHTML="Error";
document.getElementById("SignInButton").value="Sign In";
document.getElementById("SignInButton").removeAttribute("disabled");
} else {
document.getElementById("SignInButton").value="Sign In";
document.getElementById("SignInButton").removeAttribute("disabled");
}


}
});
}

Fotiman

4:17 am on Dec 27, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have only glanced at it briefly, but the first thing that stands out is that you are calling document.getElementById multiple times for the same element. Diving into the DOM can be an expensive operation, so it's more efficient to only do it once for each item you need (and store that element reference in a variable). For example:

var staffErrorBox = document.getElementById("staffErrorBox");
staffErrorBox.style.display = "block";
staffErrorBox.innerHTML = "Error";

Haven't had a chance to look closely, but that stands out to me. :)