views:

78

answers:

1

I have an image updater. I am loading by JSON the exact same file/partial that show my images.

I would like to write a loop that runs through an index and replaces every image with its equal.

This is the first div in my json object :

[{
  "photo": {
    "position":1,
    "photo_file_size":45465,
    "created_at":"2010-10-05T09:51:13-04:00",
    "updated_at":"2010-10-05T09:52:29-04:00",
    "photo_file_name":"tumblr_l0x861Yc5M1qbxc42o1_400.jpg",
    "is_cropped":true,
    "crop_h":null,
    "photo_content_type":"image/jpeg",
    "id":216,
    "caption":null,
    "crop_w":null,
    "photo_uploaded_at":null,
    "crop_x":null,
    "processing":false,
    "gallery_id":26,
    "crop_y":null
  }
},
...

The next div in that json object would be something like gallery_photos_attributes_1_id .

Update

This is what I got so far.. but the load() method doesn't work correctly. I get a "ONLY GET REQUESTS ALLOWED"

$.getJSON(url, function(data) {
for (var i = 0; i < data.length; i ++) {
  url2 = "/organizations/" + 1 + "/media/galleries/" + 26 + "/edit_photo_captions"
  var image = $("#gallery_photos_attributes_" + i + "_caption");
url_str = image.siblings("img").attr("src").substr(0, str.lastIndexOf("/"));
image.siblings("img").load(url2, image.siblings("img"));
};
})
+1  A: 

Although I'm not 100% I got you right, try this piece of code.

var url = "/organizations/" + organization + "/media/galleries/" + gallery + "/update_photo_index"
$.getJSON(url, function(data) {
  // the outer is an array, so just loop as usual
  for (var i = 0; i < data.length; i++) {
    // fetch something for the current photo
    var caption = $("#gallery_photos_attributes_"+ data[i].photo.id +"_caption");
    // update source
    caption.siblings("img").attr("src","/path/to/images/"+data[i].photo.photo_file_name+"?c="+parseInt(Math.random()*10000));
    // update caption
    caption.html(data[i].photo.caption);
    // and so on...
  }
});

Remember that in JSON "[ ... ]" describes an array whereas "{ ... }" describes an object. With an array you can just loop as with every other javascript array. If you got an object, it's like any other javascript object whose fields are accessible either with object.field or object['field']. So using JSON in javascript is nearly a no-brainer.

Hope that helps.

jek
Hey None, been looking at your code, but it doesn't seem that doing `attr` actually loads any new code or causes the image to refresh. It just replaces the attribute with the same identical attribute. How do you refresh the image though? Like the path is the same, granted, but how do I get the browser to refresh the image to see if its showing yet.
Trip
I modified the code to force the browser to refresh the image by appending a random query string to the src url (gets ignored by the web server and is the usual way to prevent caching).
jek
Clever! Change the URI, why didn't i think of that?
Trip
Awesome, thanks so much None. No one I mean. ;)
Trip