Grow your CSS skills. Land your dream job.

Run a function from within a each loop (ajax.response)

  • # April 7, 2013 at 5:37 pm

    I’m having problems trying to pass data to a function from within a each loop. I’ve roughly pasted my code below. Basically functionA gets JSON data, passes the response to functionB. I want to then pass each response item to functionC so they can be added to an array to plot markers using google maps. Any help would be appreciated. Thanks

    if(app == undefined) var app = {};

    app.Application = function() {

    this.functionA = function(){
    var self = this;

    var urlHash = location.hash;
    accessToken = urlHash.split(‘=’)[1];

    if (!accessToken) {
    return false;
    } else {
    $.getJSON(instaAPIuri+”users/” + id + “/media/recent?access_token=” + accessToken + “&callback=?”, self.functionB);
    };

    };

    this.functionB = function(response){
    var self = this;

    //Error codes
    if (response.meta.code == 400) {
    alert(response.meta.error_message);
    }

    //Create picture elements with basic information and image
    $.each(response.data, function (i, item) {

    //If item.location == null, while trying to get geolocation = error
    if (item.location != null) {
    functionC( item.location.latitude, item.location.longitude, item.images.thumbnail.url, item.user.username);
    }

    });

    };

    this.functionC = function(latitude, longitude, imgurl, user) {
    var self = this;
    var latLngPosition = new google.maps.LatLng(latitude, longitude);

    //Create marker with custom assets
    marker = new google.maps.Marker({
    position:latLngPosition,
    icon: new google.maps.MarkerImage(imgurl,
    new google.maps.Size(110, 110),
    new google.maps.Point(0,0),
    new google.maps.Point(32, 32)),
    title: user,
    map:map
    });

    //Push in array to delete later
    markersArray.push(marker);
    };

    this.init();

    };

    $(function() {

    var app = new app.Application();

    });

    # April 7, 2013 at 6:38 pm

    Pass an anonymous callback function to your $.getJSON

    $.getJSON(instaAPIuri+”users/” + id + “/media/recent?access_token=” + accessToken + “&callback=?”, function(data){
    self.functionB(data);
    });

    Your probably going to need to use your “i” counter in the each function in functionb too so that you define the correct position in the loop

    if (item.location != null) {
    functionC( item
    .location.latitude, item.location.longitude, item.images.thumbnail.url, item.user.username);
    }

    # April 7, 2013 at 7:47 pm

    Thanks for the reply Podders. The anonymous callback helped. However, I found that because I’d left out the else statement, it couldn’t push data to the next function as some items would throw an error due to not having any location data

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".