Jquery ajax not returning data

14,805

Solution 1

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

Solution 2

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());
   });
Share:
14,805
Ramazan APAYDIN
Author by

Ramazan APAYDIN

Updated on November 24, 2022

Comments

  • Ramazan APAYDIN
    Ramazan APAYDIN 12 months

    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

  • nikeaa
    nikeaa over 10 years
    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.
  • Musa
    Musa over 10 years
    There is no synchronous jsonp.