0

I'm trying to return a value from an Ajax request, but I'm getting nothing in return. I want to return the user ID from the Instagram API so I can use it in other functions. I have put the Ajax call inside a function and added async: false, but all I get is the empty string.

function getId() {
  var result = "";
  $.ajax({
    url:'https://api.instagram.com/v1/users/search',
    dataType: 'jsonp',
    type: 'GET',
    async: false, 
    data: {
      access_token: "ACCESS_TOKEN",
      q:"unsplash"
    },
    success: function(data) {
      result = data.data[0].id;
      //alert(result);
    }
  });  
  return result;
}

var id = getId();
alert(id);
Juan Vargas
  • 99
  • 3
  • 13
  • `dont use async false`..can you do console.log(data)? – guradio Jan 20 '16 at 03:54
  • @guradio you should be more specific since removing that is advised but wont actually solve the OP's problem – Wesley Smith Jan 20 '16 at 03:56
  • @JuanVagas, see the duplicate I posted above, short version is that you cant return a value like that from an asynchronous function. You can make it `async: false,` like you have (not advisable) but it would be better to use the success callback, `$.deferred`, or a `promise` to act on the value in `data` – Wesley Smith Jan 20 '16 at 03:59
  • It's not really a duplicate, as it's synchronous, but it should be a duplicate, because it shouldn't be synchronous – adeneo Jan 20 '16 at 03:59
  • @DelightedD0D I cant explain it very clearly enough. Can you do that for me? I just suggested it.I may have chosen the wrong words.But all i can say is that ajax runs on background and async false is not really needed. please correct me if i am wrong – guradio Jan 20 '16 at 03:59
  • @adeneo Exactly right :) – Wesley Smith Jan 20 '16 at 04:01
  • 1
    And using JSONP means it's always asynchronous, setting the `async` flag makes no difference with JSONP, so it really is a duplicate – adeneo Jan 20 '16 at 04:02
  • 1
    And to help you out a bit -> https://jsfiddle.net/ffb57ntu/ (and don't post your real credentials) – adeneo Jan 20 '16 at 04:03
  • @adeneo pardon me for asking this why did you use `.done` instead of `success`?i am just curious. i always use `success`. – guradio Jan 20 '16 at 04:09
  • Thanks for the suggestions, I will try them to see if I can solve the problem. – Juan Vargas Jan 20 '16 at 04:11
  • 2
    @guradio - I always use `done`, `fail` and `always`, just a habit as that's the "new" methods. Should probably get used to `then` instead, as that's more in line with ES2015 – adeneo Jan 20 '16 at 04:12
  • @adeneo i see i will also practice doing that one from now on.. thank you for clarification. happy coding mate. – guradio Jan 20 '16 at 04:16

0 Answers0