Search code examples
javascriptphpjqueryajaxflickr

How to get the API request response via AJAX


I'm trying to get the API response of Flickr via Ajax in my application. I'm using Laravel. I have a specific Route and a function to make the API calls.

//Route.php
Route::post('/getlocation/{latitude}/{longitude}', ['as'=>'get-location', 'uses'=>'FormController@getLocationImage']);

and the function

//getLocationImage()

//GET THE IMAGES BASED ON THE LOCATION FROM FLICKR.
            $api_key = 'my_api_key_is_here';
            $tag = 'night,sunset,sunrise,park,people,summer,tree,flowers';
            $lat = '&lat='.$latitude;
            $lon = '&lon='.$longitude;
            $perPage = 12;
            $url = 'https://api.flickr.com/services/rest/?method=flickr.photos.search';
            $url.= '&api_key='.$api_key;
            $url.= '&tags='.$tag;
            $url.= $lat;
            $url.= $lon;
            $url.= '&per_page='.$perPage;
            $url.= '&format=json';
            $url.= '&nojsoncallback=1';

            $response = json_decode(file_get_contents($url));
            $photo_array = $response->photos->photo;
            return Response::json(["success"=>"true", "photo_array"=>$photo_array]);

Now In a jquery function, I'm calling the Ajax.

$("#nomination-name").focus(function(){
        $.post(
            '/getlocation/'+$("#newLatitude").val()+"/"+$("#newLongitude").val(), // location of your php script
            { user: "bob", id: 1234 }, // any data you want to send to the script
            function( data ){  // a function to deal with the returned information

                alert(data);

            });
    });

But when I try to alert the data, it just shows [object Object] How can I get the response back in the Ajax call?
Output from the console is given below.

Object 
photo_array: Array[12]
0: Objectfarm: 8
id: "16325992992"
isfamily: 0
isfriend: 0
ispublic: 1
owner: "35736862@N03"
secret: "b7044c5b46"
server: "7548"
title: "#snow #trees #winter #parcangrignon #montreal #livemontreal #themainmtl #mtlblog #vscocam"
__proto__: Object
1: Object
..............

Solution

  • What you're trying to achieve shouldn't be to hard. I cannot see the contents of photo_array but as long as you know how to iterate through an object you will be fine.

    for(i=0;i<data.images.length;i++) {
        $("#images").append(data.images[i])
    }
    

    HTML

    <div id="images"></div>
    

    Here's the code you need, photo_array may not look the same but it shouldn't cause an issue just iterate through it. Here's the link to my test.