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

Error messages arising from JSON files generated by PHP

My current setup involves using a PHP script to generate a cache of JSON files. We utilize a PHP file on our server to interact with a large database, fetching result sets in JSON format for use with jQuery and other frameworks on our site. The core scrip ...

"Incorporate multiple data entries into a table with the help of Jquery

How can I store multiple values in a table row using jQuery or JavaScript when the values come from a database via Ajax? <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th ...

Menu rollout problem when clicking or hovering

I'm facing challenges in making my menu content appear when a user clicks or hovers over the hamburger menu. My app is built using Angular, and I've written some inline JavaScript and CSS to achieve this, but the results are not as expected. Here ...

Place a vertical slider adjacent to an HTML element on either the left or right side

I'm struggling to bind a range slider to the left or right side of a canvas that displays video. Despite my efforts, CSS seems to be putting up a strong fight. I can handle issues like stretching and slider values, but attaching it to the canvas is pr ...

AngularJS toaster doesn't seem to be appearing

I have integrated the angularjs toaster library into my project. Here are the necessary references: https://github.com/jirikavi/AngularJS-Toaster Added the following references for the library: <link rel="stylesheet" href="bower_components/Angu ...

forEach`` binding in knockout object

data:[ "properties": {"CountryName": "qwerty", "Population":"785004"} ] features:[ "properties": {"LastName": "abc"} ] .... Retrieving information from a JavaScript object called data and storing it in another. resultData = ...

Assess the HTML containing v-html injection

Is there a way to inject raw HTML using Vue, especially when the HTML contains Vue markup that needs to be evaluated? Consider the following example where HTML is rendered from a variable: <p v-html="markup"></p> { computed: { m ...

Sinatra application encounters internal server error resulting in AJAX request failure

I'm currently developing a game where a user's guess is submitted to the backend for evaluation and then feedback is returned in the form of an array. To achieve this, I am utilizing AJAX to fetch a set of data from a Sinatra backend. Below is th ...

Saving base64 encoded pdf on Safari

I am facing an issue with a POST call that returns a base64 PDF. The problem arises when trying to convert it to a Blob and download it using Safari browser. This method works perfectly in all other browsers. openPdf = () => { const sendObj = { ...

hapi-auth-cookie: encounters an issue while trying to read cookies for accessing restricted content

I've implemented hapi-auth-cookie for managing cookies and sessions on my website. Certain parts are restricted and can only be accessed after authentication. When a non-logged-in user tries to access these areas, they are redirected to the login rout ...

Tips for minimizing database queries for each data type

I'm currently developing an App that requires the user to input numbers into two different fields. The first field is for entering numbers, while the second field displays a calculation based on the input. Each time the user enters a number, a call to ...

Add the current date plus 48 hours to the content on a webpage (JavaScript maybe?)

Hello there, I am currently in the process of setting up a small online store for a farm using Squarespace. One thing I would like to implement is specifying that items will be available for pickup two days after they are purchased online, instead of imme ...

How can the vertical scroll bar position be reset in Material-Table when pagination is activated?

Whenever I scroll up or down in my Material-Table, and then switch pages, the vertical scroll bar doesn't reset to the top of the table. Instead, it stays where it was before changing the page, causing confusion for users. The only mention of scroll ...

Error: Validation error occurred with document - reason unknown

Recently, I've been working on developing a basic CRUD application using MongoDB as my database. However, I keep encountering an error labeled MongoError: Document failed validation, and I am struggling to pinpoint the issue. The data appears to be s ...

A guide to testing window.pageYoffset in webdriverIO using chai assertions

When conducting a selenium test using WebDriverIO and Chai, I encountered the need to capture the position of window.pageYoffset. Unfortunately, I was unable to find a direct way to do this in WebDriverIO. My initial attempts involved: browser.scroll(0, 2 ...

How do you switch selection to "hold" mode using Javascript?

In my Markdown preview area, clicking on text will cause the preview area to switch to a markdown source editor automatically, with the cursor jumping to the position corresponding to where it was clicked. function onMouseDown(e) { const range = documen ...

What is the best approach for filtering a nested array in this scenario?

Here is the response I am getting: let m = [ { name: 'Summary', subListExpanded: false, subList: [ ] }, { name: 'Upload', subListExpanded: false, subList: [ ...

What could be the reason behind ejs not allowing if else statements when the variable is undefined?

I am attempting to replicate a rather simple example from this question here <div <% if (page_name === 'overview') { %> class="menu__menu-overviewPage menu" <% } %> class="menu"> However, when I try it on a ...

Guide to automating tests on MAC using Protractor with Appium and IOS-Simulator

Is there a way to run automated tests using Protractor (or WebDriverJS) on a MAC with Appium and the IOS Simulator? We have been unsuccessful in running tests with the following configuration file, although it works fine with Selenium 2.0 - WebDriver. He ...

Is it possible for jquery JSON AJAX to block all users?

On my website, I use AJAX to load an RSS feed on the client side when the page loads. If a user repeatedly presses F5, could the owner of the RSS feed ban my entire website instead of just that one user? This would prevent others from loading the RSS feed ...