tags:

views:

41

answers:

2

Hi, i have a script that calls a php file and gets an JSON object from it. I'm tring to get the ids from the object attached to a specific element that is created by iterating with $.each the json object. Here is what i have done so far:

$(document).ready(function()
{
    $("#div2").hide('slow');
    $("#div1").empty().html('<img src="ajax-loader.gif" />');
    $.ajax(
    {
        type: 'post',
        async: true,
        url: "Parents.php",
        data: {'id' : 12200},
        dataType: "json",
        cache: false,
        success: function(json_data)
        {
            $("#div1").empty();
            $.each(json_data, function(key, value)
            {
                $("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
                $(this).data('id', key);
            });
        }
    });
    $("p.node").click(function()
    {
        var id = $(this).data('id');
        alert('The ID is: ' + id);
    });
});

What I'm trying to achieve is making every node aware of it's ID so when i click, hover etc. i can use that id to do something else like call an other php file with that id.

I'm using fireBug and fireQuery and i noticed that each paragraph that is created has an id and the value of it is the same for all plus it's the value of the last id (145).

Here is the JSON data i get from the php file (json_encode method):

{"908":"one",
 "143":"two",
 "104":"three",
 "9655":"four",
 "144":"five",
 "142":"six",
 "145":"seven"}

Tnx in advance any idea/help would be appreciated.

+1  A: 

You're assigning the data to thing json pair you're looping over...change it up a bit, like this:

$('<p class="node"><b>['+key+']</b> => '+value+'</p>').data('id', key)
                                                      .appendTo("#div1");

This creates the object using $(html), sets .data() on that, then appends it using .appendTo().


Additional fix, for anyone finding this later:

$("p.node").click(function() {

needs to be:

$("p.node").live('click', function() {
//or:
$("#div1").delegate('p.node', 'click', function() {

Since the success function runs later, the $("p.node") won't find any of the elements created in it, whereas .live() will work, even if they're created later.

Nick Craver
Tnx very very much THAT WORKED each <p> has it's correct id (fireQuery) .. god bless you .. but when i click on it the alert doesn't come up, does this have to do with the scope of the .data? or i'm completely wrong with it?
Xaris
@Xaris - The problem is that `$("p.node").click(function() {` runs *before* your `success` function, so it didn't bind click handlers to anything...so use `.live()` instead, like this: `$("p.node").live('click', function() {` :)
Nick Craver
Yeap that worked too. :) tnx much i appreciated.
Xaris
A: 

First, that's not how you set the "id" of an element. You really should do it in the markup that creates the element, because IE (if I recall correctly) gets nervous about trying to change the "id" of an existing element:

$("#div1").append('<p id="_' + key + '" class="node"><b>['+key+']</b> => '+value+'</p>');

Now you can store a data element with the "id" in it, but the data element isn't going to do you much good if you want to use the "id" to find elements for attaching handlers or whatever. (edit @Nick points out that you can't directly use those numeric keys as "id" values, if you want a real "id" on the elements.)

The other weirdness I see is that use of $(this) in the $.each callback. What is it that you expect "this" to refer to there?

Pointy
Look at his keys ;) "908", "143"...these aren't valid for the ID attribute ;)
Nick Craver
@Nick crud sorry; I'd typed an "_" but my Firefox gets so laggy if I leave it up overnight and I must have deleted it :-)
Pointy
@Pointy - Since I have usually 50-80 tabs open, switched to Chrome for *most* things now, with their [web developer extensions](https://chrome.google.com/extensions/featured/web_dev), not much reason to switch back to the slower FireFox these days, just test that the sites work in it basically :)
Nick Craver
Tnx pointy, the $(this) was for trying to get the <p> element which obviously didn't work.. the funny part is that the code i pasted was a couple changes back so the code doesn't correspond perfectly to what i describe below it :P anyway Nick (psychic?? :D) managed to help me .
Xaris