user2710234
user2710234

Reputation: 3225

Ajax GET passing the incorrect data

i have this HTML / PHP code:

$notes.='<div class="note '.$color.'" ';

    if($row["xyz"] == '') {
        $notes.='style="left:45%; top:10%; z-index:0;"><h3 align="center">New Note</h3>';
    } else {
        $notes.='style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">';
    }

    $notes.=htmlspecialchars($row['text']).'
    <a class="closeMessage">X</a><div class="addedby">'.htmlspecialchars($row['addedby']).'</div>
    <span class="data">'.$row['sequence'].'</span>
    </div>';

there are multiple containing different data from the database

i would like to use ajax to send data to a PHP page using GET, i currently have this:

$('.closeMessage').live('click',function(){
        //alert("close");
        alert($('span.data').html());
        $.get('/includes/sticky_notes/closeMessage.php',{
            sequence : $('span.data').html()
        });
        alert("close");
    });

but its passing the incorrect sequence each time. its passing the sequence number of a different row

Upvotes: 2

Views: 54

Answers (1)

Lupin
Lupin

Reputation: 1244

As your HTML code for the notes have several elements with the class 'data', when you call for $('span.data').html() you will always get the inner html of the first span with the data class.

You can traverse the dom tree and use something like the siblings function.

$(document).ready( function(){

    $('.closeMessage').on('click',function(){
      //alert("close");
      this_data = $(this).siblings('.data').html();
      alert(this_data);

      $.get('/includes/sticky_notes/closeMessage.php',{
        sequence : this_data
      });

      alert("close");
    });
});

In this example we store the data in a variable this_data = $(this).siblings('.data').html(), so we refer to the element that was clicked - $(this) and then go down in the tree until the next element with the class data.

One last thing - consider to use $('.closeMessage').on instead of live as it has been deprecated - http://api.jquery.com/live/

Upvotes: 1

Related Questions