Olga Olga - 5 months ago 50
Ajax Question

How can I automatically update stock prices every minute without refreshing the page?

I want to update stock prices on my page every minute and display new prices without refreshing the page. Could you please help me how to do this.

$(function () {
var stocks = [];
var symbols = ['AAPL', 'MSFT'];

symbols.forEach(symbol => makeAjaxCall(symbol));

function makeAjaxCall(param) {
$.ajax({
type: "GET",
url: "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=" + param + "&interval=1min&apikey=8TKKZE0GET944FMW",
success: function (result) {
stocks = result;
getPrices();
}
});
}

function getPrices() {
var metaData = stocks["Meta Data"],
timeSeries = stocks["Time Series (1min)"],
symbol = metaData["2. Symbol"];
var priceList2 = '';
Object.getOwnPropertyNames(lastDate).forEach(function (val, idx, array) {
priceList += val + ': ' + lastDate[val] + '<br>';
});

document.getElementById("demo").innerHTML += '<div class="eachStock"><a href="#" data-stock="' + symbol + '">' + symbol + '</a></div><div>' + priceList + '</div>';
}
});


My html file:

<div id="demo"></div>


Thanks!

Answer Source

First wrap all your code in a function call:

const loadData = () => {
    var stocks = [];
    var symbols = ['AAPL', 'MSFT'];

    symbols.forEach(symbol => makeAjaxCall(symbol));

    function makeAjaxCall(param) {
        $.ajax({
            type: "GET",
            url: "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=" + param + "&interval=1min&apikey=8TKKZE0GET944FMW",
            success: function (result) {
                stocks = result;
                getPrices();
            }
        });
    }

    function getPrices() {
        var metaData = stocks["Meta Data"],
            timeSeries = stocks["Time Series (1min)"],
            symbol = metaData["2. Symbol"];
        var priceList2 = '';
        Object.getOwnPropertyNames(lastDate).forEach(function (val, idx, array) {
            priceList += val + ': ' + lastDate[val] + '<br>';
        });

        document.getElementById("demo").innerHTML += '<div class="eachStock"><a href="#" data-stock="' + symbol + '">' + symbol + '</a></div><div>' + priceList + '</div>';
    }
};

You need to make sure it can be called many times, in which it mustn't append values, but replace (just clear the div at the begining, like document.getElementById("demo").innerHTML = ''). Then, you can use setInterval to call your function every so often. Don't forget to start it only when the page is loaded (you were using jquery for that, there are other options):

const TIME = 2 * 1000; // time in millis for next update
$(() => {
    loadData();
    setInterval(loadData, TIME);
});

Note that if the request takes more time than TIME, you might get concurrency issues. For a better solution, take a look at Promises. They'll allow for a cleaner code.

If you are using jquery just for request making and the 'has page loaded' event, you might want to learn newer alternatives (like the Fetch API and this event).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download