Stanky Stanky - 3 months ago 15
Javascript Question

Using the $.getJSON method bug

I'm trying to use $.getJSON for a function, and i have 2 alerts: inside1 and inside x2. When i run the site, only the first alert is processed, and the code never actually reaches the second alert. What can i do to make the code process the function? I would really appreciate help with my code.

function get_photos(searchtag){

var apikey = '#######################';

alert('inside1');

$.getJSON('api.flickr.com/services/rest/?method=flickr.photos.search&api_key=' + apikey + '&tags=' + searchtag + '&perpage=3&format=json', function (data) {
alert('inside x2');
});


Here is what the url returns (which i have double checked to be the correct URL several times):

jsonFlickrApi({
"photos": "page": 1,
"pages": 103436,
"perpage": 3,
"total": "310306",
"photo": [{
"id": "28437400284",
"owner": "20925280@N00",
"secret": "711b34701c",
"server": "8708",
"farm": 9,
"title": "20160810-DSC_0158",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}, {
"id": "29058577365",
"owner": "20925280@N00",
"secret": "bd73425d36",
"server": "8319",
"farm": 9,
"title": "20160810-DSC_0159",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}, {
"id": "28437396394",
"owner": "20925280@N00",
"secret": "7de3504657",
"server": "8877",
"farm": 9,
"title": "Sailing",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}]
}, "stat": "ok"
})

Answer

As @nnnnnn mentioned in the comments, you can't use JSON to get cross-domain data with HTTP requests in javascript. You need to use JSONP. You need to replace $.getJSON(...) with:

$.ajax({
    url: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=' + apikey + '&tags=' + searchtag + '&perpage=3&format=json',
    dataType: 'jsonp',
    success: function(data) {
        alert('inside x2');
        // You can see the response.
        alert(data);
    }
});