Troubleshooting Issues with JavaScript Counter and JSON Integration

When manually inserting a number into the HTML, the counter works fine. However, when pulling data remotely, there seems to be a problem. The remote data is logging correctly in the console and appears properly in the DOM element when the counter code is disabled. The typeof the remote data shows as "number," but using parseInt() results in "NaN." Adding a + before the variable in parseInt() gives "0" as output. I also tried encodeURIComponent(), which returned the correct value without any extra characters.

$(document).ready(() =>{

    let count;

    const getData = () => {
    
        $.ajax({
            url:'https://raw.githubusercontent.com/RAdrianKing/AUbeatweek/master/auburn.json',
            dataType: 'json',
            type: 'GET',
        }).then((response) => {
            console.log(response);
            count = response.DonorTotal;
      
            console.log(count);
            $('.count').append(count)
        })
    }

    getData()

})

And then in another js file loaded right after...

// COUNTER
 let start // set on the first step to the timestamp provided
 const elements = Array.from(document.getElementsByClassName('count')) // get the elements
 console.log(elements);

 elements.forEach(el => {
      const final = parseInt(el.textContent, 10) // parse out the final number
      console.log(final);
     const duration = 2000 // duration in ms
     const step = ts => {
     if (!start) {
         start = ts
     }
     // get the time passed as a fraction of total duration
     let progress = (ts - start) / duration 

     el.textContent = Math.floor(progress * final) // set the text
     if (progress < 1) {
         // if we're not 100% complete, request another animation frame
         requestAnimationFrame(step) 
     }
     }

     // start the animation
     requestAnimationFrame(step)
  })

Answer №1

Hey Barmar, your solution worked like a charm! Thanks a lot for the help! I relocated the second block of code inside the .then function and it did the trick!

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

Generating VueJS Syntax from JSON Data

My goal is to retrieve locale language variables from a JSON Request generated by Laravel and load them into VueJS. VueJS does not natively support locales, so I am facing issues with the ready function alert not working while the random text data variable ...

Retrieve a div element using two specific data attributes, while excluding certain other data attributes

Here are some examples of divs: <div id="1" data-effect-in="swing" data-effect-out="bounce"></div> <div id="2" data-effect-in="swing"></div> <div id="3" data-effect-out="swing"></div> <div id="4" data-effect-out data ...

Searching for specific information within a JSON file (across multiple lines)

Currently, I am working on extracting specific lines of data from a JSON file. It seems that using grep in this particular scenario might be the way to go, but I could use some guidance. Below is an example of the JSON data: [ 'vlans VLAN10 vlan-id 1 ...

The issue with MVC4 and Ajax requests for converting image ByteArrays appears to be problematic

I am attempting to change an image in my View with a click event. However, when the controller returns a byte array, the original image is replaced with an empty one. Below is the code from my Controller: [HttpPost] public byte[] GetSelectedI ...

transforming a string into a pandas dataframe using Python

I have a String variable with data that I would like to convert into a data frame using Python. I need someone to provide guidance on how to proceed. Data : data1 Name Space -------------------- ...

After fetching, null is returned; however, refreshing the page results in the object being returned. What is the

I have a specific case where I am dealing with an array of 500 post IDs and I need to retrieve the first 100 posts. To achieve this, I implemented the following code: API https://github.com/HackerNews/API BASE_URL = 'https://hacker-news.firebaseio.com ...

Deciphering complex JSON structures in PHP

I've come across a JSON structure that I need to parse. While I have managed to extract individual nested objects, it feels like there should be a simpler way to achieve this without having to search for each nested structure. Here is an example of t ...

Retrieving ng-model using ng-change in AngularJS

Here is an example of the HTML code I am currently working with: <select ng-model="country" ng-options="c.name for c in countries" ng-change="filterByCountry"></select> This HTML snippet is being populated by the following object containing a ...

What is the best way to include a RecyclerView row in the WishList feature?

I am looking to incorporate a Wishlist feature similar to Google Play in my app. Each row in my RecyclerView within the QuestionActivity contains a Button (Heart Icon). My goal is for when this heart icon is clicked, the corresponding row in the Recycler ...

Make the minimum height of one div equal to the height of another div

My query is somewhat similar to this discussion: Implementing a dynamic min-height on a div using JavaScript but with a slight twist. I am working on a dropdown menu within a WordPress site, integrated with RoyalSlider. The height of the slider div adjust ...

How to eliminate an element from numerous arrays using jQuery?

Is it possible to use jq to remove all instances of a specific name from arrays within the input data? For example, removing "Name1" from the following: { "Category1": [ { "name": "Name1", "desc": "Desc1" }, { "name": "Name ...

Issue: Error occurs when using _.sample on an array containing nested arrays

I am working with an array of arrays that looks like this: [[0,0], [0,1], [0,2], [0,3]...] My goal is to randomly select N elements from the array using Underscore's _.sample method: exampleArr = [[0,0], [0,1], [0,2], [0,3]...] _.sample(exampleArr, ...

The images on the Shopify platform are becoming increasingly fuzzy

I'm facing an issue where the images I add to my Shopify site using the Brooklyn theme appear blurry unless resized to a small scale. The dimensions of the images are 1748 x 1240 at 300dpi. My intention is to implement a JQuery image slider (lightsli ...

The function call FirstName.Val() is invalid and will not execute as intended

When attempting to create an array called requestData using the input values from a user details form, I encountered an error stating that .val() is not a function. The code snippet where this problem occurred is as follows: Jquery $('#submit' ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

Is there a way to obtain only the count result?

I am working with a connection using msnodesqlv8 and trying to count the number of records in a table. The result I am currently getting is { total: 26 }, but the expected result should be simply 26. Below is the code snippet that I am using: pool.conn ...

Steps to include all dependencies in an angular application

Managing a large Angular application can be challenging. I currently use npm install to install all packages and manually load them in my index.html file, like this: <script src="node_modules/angular/angular.js"></script> Similarly, I load ot ...

Would it be unwise to create a link to a database directly from the client?

If I want to connect my React app to Snowflake all client-side, are there any potential issues? This web app is not public-facing and can only be accessed by being part of our VPN network. I came across this Stack Overflow discussion about making API cal ...

Tips on enlarging the header size in ion-action-sheet within the VueJS framework of Ionic

Recently I started using Vue along with the ionic framework. This is a snippet of code from my application: <ion-action-sheet :is-open="isActionSheetOpen" header="Choose Payment" mode="ios" :buttons="buttons&qu ...

The Angular error TS2531 occurs when attempting to call scrollIntoView on an object that may be null

In my current Angular project, I am attempting to implement a scroll view using ViewChild by id. This is the method I have written: ngOnInit() { setTimeout(() => { if (this.router.url.includes('contact')) { ...