1

Ajax does not turn back any data.

http://jsfiddle.net/w67C4/

$.ajax({
    dataType:'jsonp',
    url: url,
    async:false,
    success: function(data){
        getUsername = data.user.id;
    },
});

Returning data is null but required to return the userId

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Cesur APAYDIN
  • 806
  • 3
  • 11
  • 24

3 Answers3

3

Your data is returned correctly :

Object {user: Object, stat: "ok"}
stat: "ok"
user: Object
  ->id: "66956608@N06"
  ->username: Object
__proto__: Object

enter image description here

This is how you can process the results :

function foo() {
    return $.ajax(...);
}

foo().done(function(result) {
    // code depending on result
}).fail(function() {
    // an error occurred
});

function getUserId() {
    var url = "http://api.flickr.com/services/rest/?jsoncallback=?&api_key=fc6c52ed4f458bd9ee506912a860e466&method=flickr.urls.lookupUser&format=json&nojsoncallback=1&url=http://www.flickr.com/photos/flickr";
    var getUsername = null;

    return $.ajax({
        dataType: 'jsonp',
        url: url,
        async: false
    });
}

getUserId().done(function (result) {
    // Call the alert here..
    alert(result.user.id);
}).fail(function(err){
      alert('an error has occured :'+err.toString());
   });
Mehdi Karamosly
  • 5,388
  • 2
  • 32
  • 50
2

You need to do this:

function getUserId() {
    var url = "http://api.flickr.com/services/rest/?jsoncallback=?&api_key=fc6c52ed4f458bd9ee506912a860e466&method=flickr.urls.lookupUser&format=json&nojsoncallback=1&url=http://www.flickr.com/photos/flickr";
    var getUsername = null;

    return $.ajax({
        dataType: 'jsonp',
        url: url,
        async: false
    });
}

getUserId().done(function (result) {
    // Call the alert here..
    alert(result.user.id);
});

FIDDLE

palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • 1
    Adding the "async: false" is what would make this answer work. That makes Javascript wait until the AJAX function has completed before it moves on with executing the function. – nikeaa Apr 29 '13 at 19:08
  • There is no synchronous jsonp. – Musa Apr 29 '13 at 19:12
0

This is because the AJAX function is called asyncronously. This means that the URL is called, and while the processing is taking place, the javascript code continues executing and returns from your function. You can see this by putting an alert for getUsername inside of your success handler. At that point you can see that the data is actually being returned correctly.

nikeaa
  • 1,047
  • 7
  • 17