Home understanding a http request and nested function in ajax
Reply: 1

understanding a http request and nested function in ajax

bom
1#
bom Published in 2017-12-07 20:13:51Z

I am referencing this code to build a twitch viewer app, which I'm having difficulties in understanding:

$(document).ready(function() {

  let usernames = ["user1", "user2", "user3", "user4"];

  usernames.forEach(function(user) {
    let http = "https://api.twitch.tv/kraken/streams/" + user;

    function getAjax(getdata) {
      $.ajax({
        url: http,
        headers: {
          'Client-ID': 'myclientid'
        },
        success: function(data) {
          getdata(data)
        }
      });
    }
  });
})

  1. What does 'headers' do exactly? I looked it up on twitch and couldn't find a detailed description. It doesn't look like it gives/adds anything to my http request. Twitch says the header "securely identify my application." but wasn't sure what that mean. I thought if it works similar to an API key it should be included in the request.

  2. What does the 'getdata' function in this code do? does it simply store the data i receive from the ajax request?

CaseyWebb
2#
CaseyWebb Reply to 2017-12-07 20:39:16Z

1) Headers are included in the request. You should be able to see them in the developer tools; this is what it looks like in Firefox

2) getdata is a callback function that is passed into getAjax by consumers, which can then act on the data as necessary, for example...

getAjax(function(data) { // do something with data })

Note also, you're redeclaring the function in each iteration of the loop, but not actually calling it anywhere. You probably want something more like this...

$(document).ready(function() {
  let usernames = ["user1", "user2", "user3", "user4"];

  function getAjax(url, getdata) {
    $.ajax({
      url: url,
      headers: {
        'Client-ID': 'myclientid'
      },
      success: function(data) {
        getdata(data)
      }
    });
  }

  usernames.forEach(function(user) {
    let http = "https://api.twitch.tv/kraken/streams/" + user;
    getAjax(http, function(data) {
      // do something with data
    })
  });
})
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.332309 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO