Luke Litherland Luke Litherland - 16 days ago 5
Ajax Question

JQuery - AJAX - How to get Data and Assign to a Div

I have a table with 3 columns (NoteID, NoteName, Note)

I essentially need to get NoteID from my php file named connectionDetails which contains the Query in it.

I currently have:

<div class="main-container-notes">
<div id="left-box">
<?php

echo "<div style='width: 100%;'>";

while( $noteName = sqlsrv_fetch_array( $resultNotes, SQLSRV_FETCH_ASSOC))
{
echo "<div class='hvr-bounce-to-right1 hover-cursor' style='width: 100%; border-right: 5px solid #00AA88; height: 50px;' id='output'>" . $noteName['NoteName'] . "</div>";
}

echo "</div>";
?>
</div>
<div id="right-box">



</div>
</div>


Each of these also needs NoteID and i need AJAX because when i click on one of these Divs the
<div id="right-box">
will display the text from the "Note" field of the table without refreshing the page.

please see my site to see what i mean

What is the best way to assign "NoteID" column respectively to each row that comes through.

Answer

Put NoteID into a data-nodeid attribute of the DIV. Then when you click on it, you can use $(this).data("noteid") to get the ID, and send it in the AJAX call.

Also, you can't use `id='output' here, because you're creating duplicate IDs on each row. You should use a class instead of ID.

So the PHP looks like:

while( $noteName = sqlsrv_fetch_array( $resultNotes, SQLSRV_FETCH_ASSOC)) 
    {
        echo "<div class='hvr-bounce-to-right1 hover-cursor output' data-noteid='{$noteName['noteID']}' style='width: 100%; border-right: 5px solid #00AA88; height: 50px;'>" . $noteName['NoteName'] . "</div>";
    }

And the Javascript would be something like:

$(".output").click(function() {
    var noteid = $(this).data("noteid");
    $("#right-box").load("ajaxscript.php", { noteid: noteid });
});