user1673498
user1673498

Reputation: 431

php Curl - JS refresh API get call

I am getting some data form an API using Curl, everything works fine and the data is parsed correctly. However this value that I'm parsing changes very regularly as its a counter.

I would like to refresh the call to update the new value every 2 or 3 seconds. How can I do this and where would I include this in Curl.php or the JS?

Curl

<?php
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'URL*(hidden)'
));
$headers = [
    'Accept: application/json',
    'Api-Key: (API KEY)',
    'Authorization: Basic (AUTH KEY)'
];
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
//print_r($resp);
echo $resp;

JS

    $(document).ready(function(){
    setInterval(function(){ 
        $.get("curldirectory.php", function(res){
          console.log(res.resource);
            var count = 1;
            var html1 = '';

            $(res.resource).each(function(i,value){

                if(value.VenueCode == "(MyCounter") {

                    html1+= '<div class="col-xs-12 hidden"><h1 class="bebas"> ' + addCommas(value.Total)  + '</h1></div>';

                }
                else{

                     html1+= '<div class="col-xs-12><h1 class="bebas"> ' + addCommas(value.Total)  + '</h1></div>';
                }

                count++;
            });

            $('#counter-list').html(html1);
        },'json');

            }, 3000);  
    });
</script>

Upvotes: 1

Views: 1265

Answers (1)

Vandolph Reyes
Vandolph Reyes

Reputation: 620

You're almost there.

function fetch_data(){
    $.ajax({
        url: 'curldirectory.php'
        type: 'get',
        success: function (data) {
            $.each($.parseJSON(data), function(){
                console.log(this.VenueCode)
                console.log(this.Total)
            });
        }
    });
}

setInterval(function() {
    fetch_data();
}, 3000);

Upvotes: 2

Related Questions