0

I'm trying to return a string of an Instagram API url. Not an object, not the data, but when getUrl() is called, it returns a string which I can then use in a getJSON later on.

The tricky bit is, thanks to the Instagram API, I first need to generate the user ID from the username (that's the getJSON you see, which works fine by the way), store that ID as user_id, then insert that ID into my string.

I understand what I have at the moment isn't working because ajax is async, and also because user_id is being used out of scope. So my question is.. what do I need to do? I feel like I'm close.

var username = foo;
var client_id = 1234567890;

function getUrl() {    

  function getUserID() {
    return 'https://api.instagram.com/v1/users/search?q=' + username + '&callback=?&client_id=' + client_id;
  }

  $.getJSON(getUserID(), function (data) {
    var user_id = data.data[0].id;
  });

  return 'https://api.instagram.com/v1/users/' + user_id + '/media/recent/?&client_id=' + client_id;

}

console.log(getUrl);
Jake Hills
  • 428
  • 1
  • 5
  • 21

1 Answers1

1

What you need to do is write a callback function that'll use the result of your ajax call. This function will receive the proper url from the asynchronous call inside getUrl(), so add whatever code that needs the url at your callback function and it'll be executed right after the $.getJSON finishes.

var username = foo;
var client_id = 1234567890;

function getUrl(getURLCallBack) {
    var user_id = 'https://api.instagram.com/v1/users/search?q=' + username + '&callback=?&client_id=' + client_id;

    $.getJSON(user_id, function (data) {
        user_id = data.data[0].id;
        var url = 'https://api.instagram.com/v1/users/' + user_id + '/media/recent/?&client_id=' + client_id;
        //Your callback function will do the magic for you
        getURLCallBack(url);
    });
}

//In this example, f will be your callback
f = function (url) {
    alert(url);
}

getUrl(f);
William Barbosa
  • 4,936
  • 2
  • 19
  • 37
  • If you really need like this, you can make your ajax call synchronous. [This post](http://stackoverflow.com/a/6685294/3465182) has everything you need to know. Please note, though, that this is against AJAX's nature and I try avoiding it (The A in AJAX stands for asynchronous, after all) – William Barbosa Jul 17 '14 at 01:06