Search code examples
jqueryajaxjsonflickr

Cant call flickr api with jQuery


Im running this code in my website to get the photos on a set, but I always end up getting error. The console log show "parsererror". What am I doing wrong?

middle.php

<?php die(file_get_contents($_REQUEST['url'])); ?>

script.js

//Flickr
var url = encodeURIComponent('http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=1408bff5f72a4b84b924d13e8562b6a2&photoset_id=77649470@N03&photoset_id=72157629903184261&format=json');
$.ajax({
    url: "middle.php?url="+url,
    dataType: "json",
    success: function(){
        console.log("yes");
    },
    error: function(jqXHR, textstatus, errorThrown){
        console.log("nooo");
        console.log( textstatus );
    }
});

Solution

  • If you're having a problem because of cross-domain security issues, you'll want to create a 'middle man' page. I will use PHP for my example. I will create a middle.php that accept a different-domain url, fetches the text/code, and returns it. My JS will see this as a same-site request, and all will be dandy.

    middle.php

    <?php die(file_get_contents($_REQUEST['url'])); ?>
    

    If PHP isn't what you use, you can apply the same strategy in your own environment.

    Then your ajax call will look like this..

    var url = encodeURIComponent('http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=1408bff5f72a4b84b924d13e8562b6a2&photoset_id=77649470@N03&photoset_id=72157629903184261&format=json');
    
    $.ajax({
        url: "middle.php?url="+url,
        dataType: "json",
        success: function(){
            console.log("yes");
        },
        error: function(jqXHR, textstatus, errorThrown){
            console.log("nooo");
            console.log( textstatus );
        }
    });
    

    However, I like to use getJSON() for fetching JSON data, more so than ajax()

    $.getJSON("middle.php?url="+url, function(obj){
        if (obj.photoset){
            console.log("Success");
        } else {
            console.log("Error");
        }
    });