I have come across a website that appears to use Ajax but does not include any js file except one file called ajax.js which has the following:
function run(c, f, b, a, d) {
var e = null;
if (b && f) {
document.getElementById(b).innerHTML = f
}
if (window.XMLHttpRequest) {
e = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
e = new ActiveXObject(Microsoft.XMLHTTP)
}
}
e.onreadystatechange = function () {
if (e.readyState == 4) {
if (e.status == 200 || e.statusText == "OK") {
if (b) {
document.getElementById(b).innerHTML = e.responseText
}
if (a) {
setTimeout(a, 0)
}
} else {
console.log("AJAX Error: " + e.status + " | " + e.statusText);
if (b && d != 1) {
document.getElementById(b).innerHTML = "AJAX Error. Please try refreshing."
}
}
}
};
e.open("GET", c, true);
e.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
e.send(null)
}
Like you might have guessed, the way it issues queries inside the page with queries like this:
run('page.php',loadingText,'ajax-test', 'LoadSamples()');
I must admit that this is the first time I’ve seen a page from which I could not figure how things are being done. I have a few questions:
- Is this Server-Side Ajax or
something similar? If not, can someone
clarify what exactly is this? - Why does one use this? Is it for hiding the design details? (which are otherwise revealed in plain text by javascript)
- How difficult would it be to convert my
existing application into this design
pattern? (maybe a subjective question but any short suggestion will do)
Any suggestions?
Not sure what you’re exactly asking here, but the function given is actually fairly simple. Decoding the variables / parameters:
Exactly why they’re using this particular method I can’t really say – seeing the complete page that uses this functionality may help.
I don’t think it’s hiding any design details. It does look a slightly odd way of doing things to me, but as I said above, there may be specific reasons for this in the way the page it’s being used in works.
Can you use this code? Certainly.
Should you use this code? The answer to that is: Is it the right tool for the job?
How difficult would it be to convert your existing code to use this method? That depends on your existing code and whether this is the right tool for the job.