Error encountered while trying to call callback functions

I encountered an error in my code, but I managed to resolve it independently. Could someone please provide an explanation of why the code wasn't working and delve into the mechanics behind the issue?

Here is the code snippet:

var listTables = function (tables) {
  console.log(tables);
}

var ajaxReq = function (success_cb, url) {
  // success_cb can be invoked here without errors
  var http = new XMLHttpRequest();
  http.onreadystatechange = function (success_cb) {
    if (this.readyState == 4 && this.status == 200) {
      success_cb(this); // Uncaught TypeError: success_cb is not a function
    }
  }
  http.open("GET", url, true);
  http.send();
}
ajaxReq(listTables, "http://www.someurl.com");

Upon removing the success_cb callback from the onreadystatechange function definition, the code ran smoothly. Is this issue related to scope?

Answer №1

The issue lies in the repetition of success_cb as a parameter within the inner function:

var ajaxReq = function (success_cb, url) { // The first usage of success_cb parameter is correct.
  var http = new XMLHttpRequest();
  http.onreadystatechange = function (success_cb) { // The second usage is incorrect!
    // ...
  }
  // ...
}

This leads to two unintended consequences:

  • It overshadows the original (first) success_cb, making it inaccessible.
  • It assigns the event argument of the readystatechange event to success_cb which results in an object.

“Overshadowing” occurs when a variable (or parameter) of the same name is provided at a closer scope than the previous one.

To resolve this issue, simply eliminate the second instance of usage:

var listTables = function (tables) {
  console.log(tables);
}

var ajaxReq = function (success_cb, url) {
  // success_cb can now be invoked here without any errors
  var http = new XMLHttpRequest();
  http.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      success_cb(this);
    }
  }
  http.open("GET", url, true);
  http.send();
}
ajaxReq(listTables, "http://www.someurl.com");

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

The concept of AJAX send function and toggling button visibility

I am facing a challenge with a textarea and send button on a panel that is displayed after entering the first character. The visibility of the button is controlled by the isButtonVisible() method. Once clicked, it sends the text from the textarea using the ...

Scrolling to the bottom of the page triggers jQuery to load additional content

Is your jQuery script not working properly when attempting to load more content upon reaching the bottom of the page? It seems to be functional on Safari/iPad and Android Mozilla browsers, but encountering issues on default Android and Chrome browsers. ...

The website is missing the display of Google Maps

The Google map is not displaying on my website page that uses PHP. I need assistance with this issue. Below is the webpage URL and the source code: <section class="meteor-google-map fullwidth block" style="height: 450px; border: solid transparent; bo ...

"Upon updating, the array within the mapped state to props in React Redux appears to be

As I work on updating a user's profile through a form, my goal is to ensure the component rerenders after the update and displays the correct information on the form once saved. Here is what I have implemented so far: ProfileInput.tsx const ProfileI ...

Updating the head() properties in Nuxt.js via asyncData() is not possible

After creating a server-side rendered Vue.js blog with Nuxt.js using Typescript and Ghost, I encountered a problem updating html metatags with data from asyncData(). According to the Nuxt.js documentation, asyncData() is triggered before loading page comp ...

Is there a way to incorporate additional text into option text without compromising the existing values?

One challenge I'm facing is adding additional text to the options without changing their values upon selection. Would you be able to assist me with resolving this issue? I have come across the following HTML code: <select id="q_c_0_a_0_name"> ...

What is the definition of XLLS?

Is there a connection between the "XLLS" expression and AJAX / Javascript? What is the actual meaning of XLLS? Thank you in advance. including text from a comment in response ...when I searched for an answer on Google, all I found was Excel XLLs but no ...

Looking to preserve the "ALL" selection in a JavaScript-CSS filter?

On the front page, there are approximately 16 posts displayed along with a filter featuring 4 drop-down menus showcasing post categories. I have assigned category names as classes to each post div and am currently using javascript to hide them. The code s ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

Issue with AngularJS compatibility on first generation iPad

Having trouble with my first generation iPad while trying to implement a basic ngRoute and ngAnimate setup. It's working fine on desktop and iPhone 6, but not on the iPad. The error message I'm encountering is: Error[$injector:modulerr]http://e ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

The prop observation was activated without any alterations

Within my component, I have a prop X that I assign to data Y during the created hook. This setup allows me to easily modify Y without affecting X. Both X and Y are Arrays. Additionally, I've set up a watch on prop X to ensure Y is updated whenever X ...

Is there a way to retrieve the `this.$route` data while using vue-apollo?

Currently working on building a GraphQL query with vue-apollo and graphql-tag. When I manually set the ID, everything runs smoothly. However, I'm aiming to dynamically pass the current route's ID as a variable to Vue Apollo. Successful Implemen ...

Tips for resolving the issue of receiving a warning about passing "onClick" to a "<Link>" component with an `href` of `#` while having "legacyBehavior" enabled in Next.js

My current project is displaying a lot of warnings in the browser console and I'm unsure about the reasons behind it. The warnings include: "onClick" was passed to with href of /discovery/edit but "legacyBehavior" was set. The l ...

Displaying feedback messages and redirecting in Flask may result in the response being visible in the developer tools, but

Just starting out with Flask and encountering an issue. I am trying to determine if a response is empty, and if it is, display a message. The problem lies in the fact that even though the redirect works and the subsequent GET request returns the correct HT ...

Arranging Check Boxes Side by Side

I am struggling to properly align the three checkboxes and tables next to each other. I have managed to get the checkboxes on the same row, but aligning them neatly has proven to be a challenge. Using Notepad++ as my development tool, I am facing formattin ...

Using jquery ajax to add new rows to a MySQL table at the bottom, creating a repeating pattern

Using AJAX jQuery, I am constantly updating a table with data from a MySQL database at regular intervals. The refresh rate is set to 1 second. Below is the PHP file responsible for successfully creating the JSON data: <?php $servername = "localhost"; ...

What could be causing the issue with the focus not being activated when clicking on the input field in Vue?

I am facing an issue where I have to click twice in order to focus on a specific input field, and I'm having trouble setting the cursor at the end of the input. I attempted to use $refs, but it seems like there may be a deeper underlying problem. Any ...

Using Express to request data from Mongo database and only receiving the path

I've been troubleshooting a websocket function that interacts with MongoDB to fetch some data stored in the system using 'get'. const User = require('mongoose'); const express = require('express'); const cal = require(&a ...

Utilizing Conditional Statements in the @artsy/fresnel Framework

I recently started working on a responsive React application using the @artsy/fresnel npm package. Below is a snippet of the code I have implemented: <Media greaterThanOrEqual='computer'> <div style={{ padding: '20px 50px' ...