Ways to keep my information current in relation to JSON updates

I have successfully created a web application that retrieves data (JSON) from the ebay API and displays it on a chart illustrating the price of each item. The current setup is working well.

However, I am eager to implement real-time updates on the chart whenever an item receives a bid or when an auction ends. All the necessary information is available in the JSON response from ebay.

The challenge I am facing is figuring out how to make the graph update automatically and trigger the ajax call either when the JSON content changes (preferred method) or at regular intervals like every 1 to 5 seconds?

$(function() {

    $.ajax({
        type: "GET",
        url: 'http://open.api.ebay.com/shopping?callname=GetMultipleItems&responseencoding=JSON&appid=&siteid=3&ItemID=350720045158,390524810753,251237014268,200902751277,140927144371&version=811',
        dataType: "jsonp",
        jsonp: "callbackname",
        crossDomain : true,
        data: { },
        success: function (result) {    

            arrayOfData = new Array();

            var items = result['Item'];

            $.each(items, function(i, item) {                   
                var title = items[i]['Title'];
                var price = items[i]['ConvertedCurrentPrice']['Value'];
                var timeleft = items[i]['TimeLeft'];                                                                        
                arrayOfData.push(['400', title + '<br/><br />' + timeleft]);                
            });

            $('#graph').jqBarGraph({
                data: arrayOfData,
                height: 800,
                width: 1200,
                barSpace: 20,
                colors: ['#085497','#74b3ea'],
                prefix: '£'
            });                                     

        },
        error: function (data) {
            console.log(arguments);
        }
    });

 });

Answer №1

Implement an ajax call within a setInterval function:

setInterval(function(){
    //make your ajax call here
}, 10 * 1000);

Answer №2

If you're looking to react only when the price changes, here's a simple approach you can take. It may need some fine-tuning for your specific requirements:

$(function() {

var previous_prices = {};     // object to store past prices

// function for updating the chart
var update_graph = function (data_to_display)
{
     $('#graph').jqBarGraph({
         data: data_to_display,
         height: 800,
         width: 1200,
         barSpace: 20,
         colors: ['#085497','#74b3ea'],
         prefix: '£'
     });                                      
};

$.ajax({
    //...bla bla bla...

        success: function (result) {    

            var data_array = [];

            var items = result['Item'];

            $.each(items, function(i, item) {

                var title = items[i]['Title'];
                var price = items[i]['ConvertedCurrentPrice']['Value'];

                if (!previous_prices[title] || previous_prices[title] !== price)
                {
                    data_array.push(title + '<br/><br />' + price);
                }
                
                previous_prices[title] = price;
            });

            if (data_array.length > 0)
            {
                 update_graph(data_array);
            }

    });

});

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

Tips for accessing a value in a json object by using another value within the object itself

I need to extract a specific value from a JSON object in order to retrieve another related item within the same object. My goal is to input the "Abbv" value into the JSON Object and retrieve the corresponding "Set" value. [ {"Abbv": "VIS", "Set": "Vi ...

z-index not functioning properly

Currently, I'm diving into the world of custom map creation using Leaflet and Mapbox. Everything was going smoothly until I encountered a challenge with the popups. Here's the issue: I have a unique navigation/control panel that I want to displa ...

Tips for troubleshooting Node.js React Express applications

Having a background in traditional programming, I am used to putting breakpoints in code and having the debugger take me directly to the problematic section when executed. However, as I delve into web app development, it seems that debugging is limited to ...

Callback is triggered after ng-if removes the directive from the scope

A scenario on my page involves an angular directive nested within ng-if. I've developed a service that features a function, let's name it functionX, capable of accepting a callback as an argument. Whenever the ng-if condition becomes true, the ...

Leveraging the power of the .includes() method

Here is a question regarding the issue at hand. To tackle this problem, create a function called checkForPlagiarism with two parameters: an array containing responses from a specific individual and a string representing an external source. The function sh ...

How to Change Text When Accordion is Expanded or Collapsed using Javascript

Help needed with JavaScript accordion menu for displaying indicators in front of section headers. The goal is to show a (+) when collapsed and (-) when expanded. The current code only changes on click, not based on the section's state. Looking for fre ...

Obtaining a string value through a promise retrieval

Within the following code snippet, I am executing an HTTP request where I extract a "token" (a string) from the response. My objective is to assign this token value to the variable foo. foo = request.post( { url: 'http://10.211.55 ...

The error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify th ...

Is your preference selecting made a breeze by dragging the input field?

Looking to create a form that allows users to indicate their preference between Option A and Option B by dragging a slider. I know there must be a library out there that already does this, but I can't seem to figure out what it's called to searc ...

Locating the specific row associated with a cell using jQuery

I’m new to programming and currently learning JQuery. I have a query: if there is a button in a column attribute, and upon clicking the button in that cell, I want to retrieve the unique ID value for that cell. For example, if my attribute name is "app ...

Prevent animations on child elements with Vue.js

I am dealing with a scenario where I want to remove the fade transition on a child div within a <transition> component. The reason for nesting it is to prevent layout flickering, which can be demonstrated in a fiddle if necessary. In the fiddle belo ...

Remove cached documents and database entries using AJAX

When utilizing ajax to delete files from both the database and local, I am encountering an issue with deleting the correct file from the local storage. It seems that I am unable to pass the correct file name as it keeps deleting the top file listed on the ...

Why does the data loaded from PHP using jQuery vanish suddenly?

After conducting a thorough search to avoid duplication, I couldn't find a similar post, so my apologies in advance if there is one. Here is my current issue: Why does the data, as shown in the code below, load momentarily and then disappear? CSS ...

Generating div elements of varying colors using a combination of Jinja templating and JavaScript loop

Utilizing jinja and javascript in my template, I am creating multiple rows of 100 boxes where the color of each box depends on the data associated with that row. For instance, if a row in my dataset looks like this: year men women 1988 60 40 The co ...

Arrange items in a particular order

I need help sorting the object below by name. The desired order is 1)balloon 2)term 3)instalment. loanAdjustmentList = [ { "description": "Restructure Option", "name": "instalment", " ...

Tips for customizing the appearance of a jQuery sortable target list prior to dropping items

When using jquery sortable, I am able to customize a placeholder inside a connected list specified in the connectWith option to visualize where the content will be dropped. However, I am struggling to find a way to style the actual list that contains the p ...

retrieving the value of a field within an array

Here is my code snippet: <div class="label">{{ item.data[0] }}</div> and in the view, this is what I have: { "id": 6, "firtname": "JHON ", "lastname": "SCALA", "fullname& ...

The escape character appears to be misunderstood, causing an error due to an invalid escape sequence

When using the following syntax: executeJSCommand("location.href='StatusDetails.php?CHLD=1\&JNum=1024&JTitle=';"); An error occurs displaying: Invalid Escape Sequence ...

Submission form fails to go through or button for submitting is malfunctioning

After researching, I believed that this code would function properly. However, upon implementation, it is not working as expected. The main issue is that the form is failing to submit. How can I troubleshoot this problem? Furthermore, I am unable to re ...

Guide to generating touch interactions with Angular 2 and beyond

What are some methods for implementing touch events in Angular, since Angular does not natively support touch events like (click)? ...