Currently, I'm working on developing a function that utilizes AJAX to call data from another server and then processes the returned data using a callback. My goal is to be able to make multiple calls to different URLs and use the distinct responses in separate functions.
However, when I make two calls, it only retrieves one dataset (battlefield). I am puzzled as to what I might be missing in this setup.
Interestingly, everything works perfectly fine if I make just one call (e.g., to Treehouse).
/* This function checks for AJAX availability and creates an AJAX request accordingly.
* Params: url - the API URL
* type - the type of request (GET, POST) - default is GET
* callback - function to process the AJAX response
*/
function makeRequest(url, type, callback) {
type = typeof type !== 'undefined' ? type : 'GET';
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function(){
try {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
return callback(response);
} else {
alert('There was a problem with the request.');
}
}
} catch(e) {
alert('Caught Exception: ' + e.description);
}
}
httpRequest.open(type, url);
httpRequest.send();
}
Here's how I am calling the function:
makeRequest('//teamtreehouse.com/davidendersby.json', 'GET', function(treehouseData){
console.log(treehouseData);
sortedTreehousePoints = sortObject(treehouseData.points, 'DESC');
getTotalPoints(treehouseData);
getPoints();
getTreehouseBadges(treehouseData);
});
// Not Working:
makeRequest('http://api.bf4stats.com/api/playerInfo?plat=xone&name=davetherave2010&output=json','POST', function(battlefieldData){
console.log(battlefieldData);
});