简体   繁体   中英

How do i display unique php data using javascript

i have this little project i'm working on which stores data in a database using php then loads all saved data as lists into a div asynchronously. it works fine but i am currently facing a php-javascript crisis ...Here is a summary of what happens

Expected result:

  • when a list is clicked, display the unique clicked title

Actual result:

  • Always displays the title that was last saved even when a different one is clicked.

Please guys i need help to achieve the 'expected' result.

here is a snippet of the php code

//users name
$uname = $_SESSION['username'];

//establishing connection to notes database
$dbconn = mysqli_connect('localhost','root','','notesdb');
if(!$dbconn){
    die("Connection failed:". mysqli_connect_error($dbconn));
}

//order by desc i.e Most recent appears always at the top
$result1 = mysqli_query($dbconn,"SELECT * FROM notes_log ORDER BY id DESC");
/*
loops through the query result and presents it in  an array i.e 
'username:title:body:date' and is displayed in the notes-log div.
*/
while($extract = mysqli_fetch_array($result1)){
if($extract['username'] === $uname){
    $title = $extract['note-title']; 
echo "<div class='saved-note' >";
echo "<a href='#'><span id='note-title' class='note-title' onclick='displayNote()'>". truncate($title) ."</span></a>";
echo "<div class='trig-dropdown'><span class='fa fa-ellipsis-v' id='fa-ellipsis-v'></span><div class='dropdowncontent-noteslog' id='dropdowncontent-noteslog'><a href='#'>delete</a></div></div>";
echo " <span id='note-date'> " .$extract['date-saved']."</span>";
echo "</div>";
}

}

JS

function displayNote(){
var res = document.getElementById("note-title");
alert(res.innerHTML);     
}

Method 1:

Try passing this in your onclick function,

<span id='note-title' class='note-title' onclick='displayNote(this)'>

and get your parameter on javascript also.

<script type="text/javascript">
function displayNote(this){
  alert(this.innerHTML)
}</script>

That should work.

Note: It would be better if you make your id unique every loop.


Method 2:

Make your id unique for each loop.

echo "<span id='note-title-".$i."' class='note-title' onclick='displayNote()'>"

Your ids would be note-title-0 , note-title-1 , ... and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM