skip to Main Content

I am creating a website using Django on the stock market. I am fetching the live stock market data from an API. I want to update the live price of a stock every 5 seconds (which is given by the API). How can I do this without refreshing the page? I found that Ajax is very helpful for this but I am not being able to implement this properly. Thus, can someone please give an example of the code which is required in the Html page to update the values using Ajax. I was thinking of using a separate URL that could send the data in a JSON format. Please help me out if possible.

2

Answers


  1. You need to use setInterval or setTimeout:

    Using ES5

    var $price = $('#price');
    
    var interval = setInterval(function() {
       fetch('api').then(function(res) {
          return res.json();
       }).then(function(json) {
          $price.html(json.price);
       });
    }, 1000);
    

    using more modern JavaScript:

    const $price = $('#price');
    
    var interval = setInterval(async function() {
       const res = await fetch('api');
       const json = await res.json();
       $price.html(json.price);
    }, 1000);
    
    Login or Signup to reply.
  2. For this purpose you better use django channels
    You will need to use asynchronous django views and I think this is the most accurate way to do your job

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search