In order to make AJAX requests using pure JavaScript, you need to do something like this:
httpRequest = new XMLHttpRequest();
// Specify a function to handle the response.
httpRequest.onreadystatechange = function() {
// Process the AJAX response in here.
}
// Make the AJAX request
httpRequest.open('GET', 'http://prajjwal.com/profile.json', true);
The first parameter to open is the type of request that you want to make. We make a 'GET' request in this case. The second argument is the url of the item that you're trying to retrieve. The third argument is a boolean that decides whether the request should be asynchronous or not. If the request is async, your function will not halt & wait for the request to finish.
It is also worth noting that this won't work in Internet Explorer 8 or below. To support those browsers, you need to use:
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
To handle the response, your handler needs to have something like this:
function handleRequest() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
yourdiv.innerHTML = httpRequest.responseText;
} else {
console.log('There was a problem with the request.');
}
}
}
httpRequest.onreadystatechange = handleRequest;
httpRequest.readyState tells you how the request is progressing. A value of 4 means that the request is complete & ready to be processed.
Keep in mind that you cannot request resources on other domains with open().
load
functions in jQuery, and I'd argue that the one I thought of is the more commonly used one. – Felix Kling Mar 25 '14 at 10:04