Making an HTTP GET request to a REST API endpoint

1.3k views Asked by At

Making a HTTP GET request to https://api.iflychat.com/users/list/demo/c-g

The above URL returns the list of online users on a website in JSON format. Each entry in the result array has following properties (except the last one):

• u – id of the user

• n – name of the user

• s – status of the user

• p – profile URL of the user

The last element in the result array indicates the total number of users in the list.

I want to render this list in my web application and update the data every minute.

var $Form = $('form'), $Container = $('#container');
$Container.hide();
$Form.on('submit', function(p_oEvent){
var sUrl, oData;
p_oEvent.preventDefault();
sUrl = 'https://api.iflychat.com/users/list/demo/c-g'
$.ajax(sUrl, {
    complete: function(p_oXHR, p_sStatus){
        oData = $.parseJSON(p_oXHR.responseText);
        console.log(oData);
        alert(oData);
        $Container.find('.userId').text(oData.u);
        $Container.find('.name').text(oData.n);
        $Container.find('.image').html('<img src="' + oData.p + '"/>');
        $Container.find('.status').text(oData.s);
        $Container.show();
    }
 });    
});

This is my current JavaScript code.There is a submit button on HTML page. I am new to json parsing through REST APIs please help me to parse the list into object array. And the list should be updated after every 1 minute.

1

There are 1 answers

0
Tobi On

I reduced your code to the essential problem and it seems, your API returns 'application/json' content, which is parsed by jQuery already into an array of objects. Please find a working example below, which will also check if data is a string and then parse it into an object. Please be aware that you might add some errer handling in case the API returns errors in string format and not in valid JSON.

Edit: added setInterval.

function getCurrentUserList(){
  sUrl = 'https://api.iflychat.com/users/list/demo/c-g'
  $.get(sUrl, function(data, status){
    console.log("status:", status);
    var oData;
    if(typeof(data) === "string"){
      //just in case the result is not already of type 'object'
      //TODO: needs error handling
      oData = JSON.parse(data);
    }else{
      //this is what should happen in most cases for the given API
      oData = data;
    }
  
    //display data form the second entry:
    console.log(oData[1].n);
    console.log(oData[1].s); 
    console.log(oData[1].p);   
  });
}

//get data now
getCurrentUserList();

//get data every 5 seconds:
setInterval(getCurrentUserList,5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>