user9888683
user9888683

Reputation:

Ajax load data from API without click or page-refresh

When data value change, Ajaxshould load data without any click or refresh page.

Here is what i tired.

        $.getJSON('www.yourtradelog.com/api/first-hour-trades', function(data) {
            $.each(data, function(firstHourTrades, element) {
                $("#msg1").append($('<div>', {
                    text: element.first
                }));
            });
        });
<div class="row">
    <div class="col-6 col-sm-4">  <p id = 'msg1'> first</p> </div>
   
</div>

Why I have to Refresh the page when i want t load it? I dont want click or page refresh.

Upvotes: 1

Views: 851

Answers (1)

Thimira Amaratunga
Thimira Amaratunga

Reputation: 66

Since the AJAX call is initiated from the page, it would not know that the data has changed in the backend. One simple solution would be to use a setInterval in the JS to periodically check for data from backend. But this is not a recommended method.

setInterval(function(){ 
$.getJSON('www.yourtradelog.com/api/first-hour-trades', function(data) {
        $.each(data, function(firstHourTrades, element) {
            $("#msg1").append($('<div>', {
                text: element.first
            }));
        });
    });
}, 10000);

A more complete solution would be to use WebSockets from the backend to push data to the frontend.

Upvotes: 1

Related Questions