Guide to making a reusable AJAX function in JavaScript

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);
});

Answer №1

Seems like the variable `httpRequest` is currently declared in the global namespace. Remember to use var keyword for proper scoping. Here's an example:

function makeRequest(url, type, callback) {
type = typeof type !== 'undefined' ? type : 'GET';
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
   httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    ...

Answer №2

The only issue I can see is related to Best Practices, as well as receiving multiple responses. (On Line 67, there's a console.log(battlefieldData); and on Line 58, there's a console.log(treehouseData);)

I recommend checking your XAMPP, WAMP, Apache server or whatever you are using, and also trying out jQuery Ajax along with the shorthand methods $.get() and $.post()

EDIT There might be an issue with referential integrity due to both requests being ASYNC, but I'm not entirely certain about this.

EDIT 2 When mentioning referential integrity, I meant in the JavaScript environment rather than in the context of database referential integrity. The link provided may be misleading.

Answer №3

Your assistance has been greatly appreciated. The problem turned out to be a scoping issue, which was resolved by declaring the httpRequest variable inside the function.

While I have some familiarity with jquery, I am now expanding my expertise in pure javascript. I will be sure to explore strict mode further.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I display the output from Geocoder in a text box using the ArcGIS JavaScript API?

I am trying to customize the Geocoder text box in the ArcGIS JavaScript API by overriding the default search result. Although I have written some code for this purpose, I am not satisfied with the results. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...

Is there a way to verify if a FormData file has no content?

Currently working on an AJAX form where users can choose a background color or upload a background image. The aim is to have the bgColor field ignored if a file is specified for bgImg. <label>Color: <input type="color" name="bgColor" value="#0000 ...

Experiencing difficulties accessing the API route through Express

Every time I attempt to access /api/file, I am receiving a status code of 404. Here is the relevant code snippet: app.js : ... app.use("/api", require("./routes/users")); app.use("/api", require("./routes/file")); ...

Exploring the syntax of ReactJS state management with setState

Trying to wrap my head around the following syntax in my React app. I am looking to understand how the code inside setState() works. this.getSomePromise().then( // resolve callback function someImg => this.setState(prevState => ( ...

Maintaining aspect ratio of canvas while ensuring responsiveness

Currently, I am working on a drawing app and have come across an issue that has been challenging for me to resolve. The dilemma lies in resizing the canvas of sketches from the original resolution of 1280 x 720 to the maximum size possible upon opening the ...

Exploring various layers of nested data

I am currently developing a comprehensive global data storage system for my application (specifically an Angular JS app - although this question pertains to JavaScript in general). I have established a 'service' that is responsible for setting t ...

Extract the content from the division and set it as the image source

Looking for a way to retrieve the content from a div and insert that into the 'src' parameter of an image. Working on a project where JSON is used to load translation files, preventing me from loading images directly, but I want to at least load ...

Sending a JavaScript string to a PHP script from a Chrome extension content script

I am currently developing a chrome extension that is designed to extract text data from specific websites when I visit them, and then store this data in a SQL database. The JavaScript code for data extraction is functioning correctly and is able to capture ...

What is the best method for calculating the total of a mongoose attribute?

I am attempting to calculate the sum of schema using reduce. However, the current code is not adding the items together but rather placing them next to each other. For example, 20 + 30 should result in 50, but instead it gives me 02030. Is there an issue w ...

Using node.js to trigger events from an object

In my node.js module, I have the following setup: var object = {}; object.property1 = "value1"; object.property2 = "value2"; asyncFunction(function(data) { object.property3 = data; // My goal is to: object.emit("finished"); }); module.exports ...

Locating the elusive sequence number within a document

Greetings, I am currently trying to locate a missing number within an xml file but seem to be encountering some challenges. Any suggestions or ideas would be greatly appreciated. Example The file contains an <a> tag with various ids such as page-1, ...

Modifying Stroke color in HTML5 Canvas

I am attempting to create a unique visual effect by drawing a circle resembling a clock using canvas 2d context. The idea is to initially draw the circle in black starting at point p1, and then when I complete a full circle tour it should erase as the colo ...

Removing a Dynamic Element in ReactJS

--CustomFieldSection.js-- import React, { Component } from 'react'; import CustomField from './CustomField.js'; class CustomFieldSection extends Component{ constructor(props){ super(props); this.stat ...

Enhancing jquery datatable functionality with data-* attributes

I successfully added an id to each row of my data table using the rowId property, as outlined in the documentation. $('#myTable').DataTable( { ajax: '/api/staff', rowId: 'staffId' } ); Now I am wondering how I can ad ...

Display the element solely when the user enters a value greater than 0 into the input box

I am in the process of developing a WoW Classic statistics calculator that allows users to select a class and input various values. As the user makes changes to the inputs, the calculations are displayed below the form using vanilla JS and jQuery. I am ple ...

Retrieving the selected date from JqueryUI Datepicker after form submission

I am currently using an inline datepicker that fills in an input textbox. $("#left-calendar").datepicker({ altField: "#left-date-text" }); The left-date-text is located within a form, and upon submission with a submit button, it sends the data to a p ...

Command handler that dynamically utilizes both shared and separate commands

Currently, I am in the process of setting up a command handler for multiple channels on Twitch. To organize the commands, I have them divided into specific folders for each user and generic ones. Accessing these commands is done by using a map(). My goal i ...

I used npm to install AngularJS and then included AngularJS in my application

My goal is to set up AngularJS v1.5.x using npm and integrate it into my application for seamless utilization. Most tutorials opt for downloading the Angular Version from angularjs.org and manually adding it to the index.html within a <script></sc ...

the dropdown menu toggle is not working as expected

My dropdown icon is not appearing and the menu options are not functioning properly. Despite trying to use a script to display the text when an option is clicked, it doesn't seem to be working. It appears that the toggle functionality is not working ...

Using underscore.js to connect an object with $rootscope: a step-by-step guide

I have a variable storing data var tooltipsJson = [{ "Language": "en-GB", "Section": "Sales&Marketing", "ItemName": "CalculationType", "Texts": "Having selected the account heading select the calculation ..." }, { "Language": " ...