Updates to class variable values in jQuery are failing to take effect

Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right!

function ClassName(productId) {

    //initialize variables
    this.productId = productId;
    this.shop = [];
    this.product = [];

  //method that triggers a response. On success, {"status" : "success", "shop" : "someshop.com"} is returned
  this.auth = function() {
        $.ajax({
            url: "http://website.com/api/auth/",
            dataType: "jsonp",
            success: function(data) {
              authCallback(data); //utilize callback to manage response
            },
            error: function() {
                console.log("bad auth");
            }
        });     
    }

  var authCallback = function(r) {
    //confirm the response with console.log(r)
    this.shop = r; //no errors here
  }

}

In the authCallback method, I'm assigning r to this.shop, however, when I check the value of this variable later on, it remains at its initial [].

var classInstance = new ClassName(1);
classInstance.auth();
console.log(classInstance.shop); //displays [] 

I even experimented in the JavaScript console by executing each line consecutively after every stage was completed (waiting for the response from classInstance.auth() and output from authCallback() before calling console.log(classInstance.shop);)

What am I missing? Why isn't the variable reflecting the updated value?

Answer №1

If you simply write:

authCallback(data);

then the value of this within the authCallback function may be incorrect, either null or referring to the global object (depending on strict mode).

To ensure that this inside the callback refers to your object, use:

success: authCallback.bind(this)

It is important to note that you cannot access this.shop until after the callback has finished executing. A more modern and idiomatic implementation using jQuery techniques would be as follows:

this.auth = function() {
    return $.ajax({
        url: "http://website.com/api/auth/",
        dataType: "jsonp"
    }).done(this.authCallback.bind(this)).fail(function() {
        console.log("bad auth");
    });
};

this.authCallback = function(r) {
    this.shop = r;
    return this;
}

And then:

var clazz = new ClassName(1);
clazz.auth().then(function(c) {
   console.log(c.shop);
});

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

Is my front-end JavaScript fetch request mistakenly being sent as a GET instead of a POST?

On clicking the submit button, a fetch request is triggered. Strangely, in the developer tools, it shows up as a GET request. I tested the request using Insomnia and it returned the handlebars site to me without any of my console logs appearing on either ...

Is the JSON response in the AJAX request accurate, even though the content is not being refreshed?

I have a function that is triggered in the following manner: success: function(json) { if(json.valid == 1) { // Another show/hide operation that functions properly $("#div-response-" + id).html(json.message); } ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

Angular Testing - issue with promise returning unexpected results

I'm having trouble with populating vm.chartData in my HomeCtrl. Even though I've mocked data to it in the beforeEach() function, when I console.log(scope.vm.chartData), it returns undefined. However, other scope variables like graphLoading are pr ...

The specified container does not exist in the DOM: MERN

I am currently working on a project where I aim to develop a Web Application featuring a stock dashboard. During my coding process, I encountered a minor issue that can be seen in this image. My goal is to have a login form displayed on the browser using ...

Tips for converting HTML content into a properly formatted text file

I have a user interface where users can perform various actions using ajax calls. Once the ajax call is completed, the results are displayed in a div with an id = "log". I want to provide users with an option (a button labeled Export) so that when they hav ...

Include form data into an array of objects within an Angular data source

I am struggling to add the edited form data from edit-customers-dialog.ts into an array of objects in my datasource. The form.data.value is returning correctly, but I'm facing issues with inserting it properly into the array. As a beginner in Angular ...

Input field modified upon focus

I am currently using selectize js in my section to create a select box. My goal is to make the input editable after selecting an option when it is focused on. Check out the live demo: live demo HTML <label>Single selection <select id=" ...

Iterate through a jQuery function to retrieve values from checkboxes starting from the 4th one that has been clicked

I am currently using a loop in a form to calculate the total price of a product based on user selections. However, I have encountered a challenging task where certain checkbox groups have specific rules. For instance, group A should only contribute to the ...

typescriptUsing redux: prevent parent component from accessing redux props

I'm currently using redux and typescript in my webapp project. What's the best approach for defining props in a component that receives redux-actions through @connect, as well as props from its parent? // mychild.tsx export namespace MyChildCom ...

Sending information from a dynamic table to a database using PHP

I've created an HTML webpage with a table that fetches data from my database. Each row in the table has a button that, when clicked, dynamically adds the data into another table on the webpage using JavaScript. The dynamic table includes a submit butt ...

Issue with jQuery selector when handling AJAX response

I've been scratching my head trying to understand why this code isn't functioning as expected. To make things clearer, I created a simplified version of the issue on jsFiddle, where it works perfectly. Here's what I'm trying to achieve ...

"Enable a smooth transition and switch the visibility of a div element when clicked

How to create a dropdown form with a transition effect that triggers on click of an element? Once triggered, the transition works smoothly but clicking again only hides the div element without triggering the transition. See the demo here: Check out the fu ...

Laravel triggers a 'required' error message when all fields have been filled

As I attempt to submit a form using an axios post request in laravel, I encounter an issue with the validation of the name and age fields, along with an image file upload. Here is a breakdown of the form structure: Below is the form setup: <form actio ...

What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one. var ...

Tips on showing database information with JavaScript

<script type="text/javascript"> var content = { metadata: ['January', 'February', 'March', 'April'], infoSets: [ { fillColor: "rgba(220,220,220,0.2)", strokeCol ...

Memory Match: Picture Edition

In this memory game, letters are used. I had considered changing it to a picture-based game, but I faced difficulty in generating images and incorporating them into the array. <script> var memory_array = ['A', 'A', 'B&ap ...

Unraveling the Enigma of Event Handlers: Mastering the Organization of a Sprawling jQuery File within an AJAX

I've created a web application that heavily relies on AJAX and jQuery for DOM manipulation and making AJAX requests. However, I'm facing a problem with my JavaScript file: The issue is that my JavaScript file consists of a huge collection of eve ...

Using node.js to parse an XML file from a URL and iterate through it to retrieve all the URLs contained within

I am currently utilizing the node module xml2js. The format of my xml file looks like this: <?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl"?> <?xml-stylesheet type="text/css" media="screen" href="some url" ?> ...

Reply in Loopback on remote method beforeRemote hook is to be sent

In my application, I am utilizing loopback v3. The specific use case I am tackling involves validating the presence of a token in the request header. If the token is invalid, I need to send an appropriate message in a standardized format. My approach has b ...