holyredbeard
holyredbeard

Reputation: 21198

How to store data retrieved through AJAX for later use

I have an application that opens a div with several thumbnails of images. When clicking on an image a new div shall open with the image in full size, and the div shall have the same width and height as the image.

From the php file I retrive objects with several parameters, eg. thumbWidth/thumbHeight and width/height. What I need to do is to store the width and height for every image, so that I can open a div with the correct size. What is the best way to do it? I guess I could store width and height in a multi dimensional array, but I guess there is a better way?

As you can see in the code below I tried to store eg. this.width in the variable 'imgWidth' and apply it to the event, but every image get the last retrieved width and height so that doesn't work.

$.getJSON('...getJSONThumbs.php', function(json) {
    $.each(json, function() {

        if (this.thumbWidth > maxWidth){
            maxWidth = this.thumbWidth;
        }

        if (this.thumbHeight > maxHeight){
            maxHeight = this.thumbHeight;
        }

        var box = $('<div/>', {
            'class': 'imgDiv',
            'width': maxWidth,
            'height': maxHeight,
        }).appendTo('.imageArea:last');

        var a = $('<a/>', {
            'href': '#',
        }).appendTo(box)

        var img = $('<img/>', {
            'src': 'pics/' + this.fileName,
            'width': this.thumbWidth,
            'height': this.thumbHeight,
        }).appendTo(a);

        imgWidth = this.width;
        imgHeight = this.height;

        box.click(function(event) {
            event.preventDefault();
            console(imgWidth + " " + imgHeight);    // always the last images width and height
            $('#desktop').css("background-image", "url(" + img.attr('src') + ")");  
        });

        jQuery(loaderImage).hide();
    });
});

Upvotes: 1

Views: 475

Answers (1)

Didier Ghys
Didier Ghys

Reputation: 30666

jQuery provides a way to associate data to elements through the .data() method.

As you bind the handler on the box object, I would add the data there, like this:

box.data('imgWidth', this.width);

You retrieve the value with:

var width = box.data('imgWidth');

Applied to your code I would do this:

var params = this; // for the sake of the example (the current json object)

var box = $('<div/>', {
    'class': 'imgDiv',
    'width': maxWidth,
    'height': maxHeight,
})
.data('imgSize', params); // save the data to the element
.appendTo('.imageArea:last');

...

box.click(function(event) {
    event.preventDefault();

    // get back the saved data
    var savedParams = $(this).data('imgSize');
    console(savedParams.width + " " + savedParams.height);

    $('#desktop').css("background-image", "url(" + img.attr('src') + ")");  
});

Upvotes: 2

Related Questions