0

i'm having a problem here, in the success method of AJAX i have a if to see if the Streamer is live or not, if is live it returns "online.png" and if is not it returns "offline.png", my problem is that the returns give "undefined" but if i uncomment the console.log in console i can see "offline.png" or "online.png" on console (but the returns still giving undefined). Someone already pass this problem?? Thanks

function checkOnline(nombre){

  try {


$.ajax({
  type: 'GET',
  url: 'https://api.twitch.tv/kraken/streams/' + nombre,
  headers: {
    'Client-ID': '
  },
  success: function(data) {
  //  console.log(data["stream"]);
    if (data["stream"] == null) {
      return "offline.png";
      break;
    //  console.log("offline.png");
    }else {
      return "online.png";
      break;
      //console.log("online.png");
    }
  },
  error: function(data){
    alert("Stream not found!");
  }

});
  } catch (e) {
    alert("Conection error, try later... Monkeys are fixing it");
  }


}
ecg8
  • 1,362
  • 1
  • 12
  • 16

2 Answers2

1

There is no need for return or break in this context. Nothing can be returned in an asynchronous request and you are not in an iteration, so there is nothing to break out of.

The function checkOnline is always going to return undefined, because it is an asynchronous call, it can not break out and return the result of the request.

If you want to do something with the data, you can do it directly within the callback method.

Anthony L
  • 2,159
  • 13
  • 25
0

You can make something like that:

function checkOnline(nombre, callback){

  try {


$.ajax({
  type: 'GET',
  url: 'https://api.twitch.tv/kraken/streams/' + nombre,
  headers: {
    'Client-ID': ''
  },
  success: function(data) {
  //  console.log(data["stream"]);
    if (data["stream"] == null) {
      callback("offline.png");
      break;
    //  console.log("offline.png");
    }else {
      callback("online.png");
      break;
      //console.log("online.png");
    }
  },
  error: function(data){
    alert("Stream not found!");
  }

});
  } catch (e) {
    alert("Conection error, try later... Monkeys are fixing it");
  }

    return result;
}

Actually now you return value from success function, not from checkOnline function. You can provide a callback for process result of async call of ajax function.

Serega
  • 630
  • 1
  • 4
  • 12