Reputation: 53
So I want to set up my index.php so that when the like button is clicked, ajax is used to go to liked_button.php and change the look of the button to 'Liked'. This works, for one button, the first button. It doesn't work for all the other buttons on the page. Liking another button other than the first button, makes it appear as if the first button was liked. So my question is, how do I apply this ajax code to 'ALL' of the like buttons on index.php?
Here is the index.php :
<!doctype html>
<head>
<?php
include('header.php');
?>
<script>
$(document).ready(function(){
$(".button").click(function(){
$.ajax({url:"liked_button.php",success:function(result){
$("#like_system").html(result);
}});
});
});
</script>
</head>
<link type="text/css" rel="stylesheet" href="index.css">
<body>
<?php
$conn = mysqli_connect("localhost","root","") or die ("No SQLI");
mysqli_select_db($conn, "sample") or die ("No DB");
$sqli = "SELECT * FROM `photos` ORDER BY `id` DESC";
$result = mysqli_query($conn, $sqli) or die ("No query");
while($row = mysqli_fetch_assoc($result))
{
$username = $row['username'];
$title = $row['title'];
$description = $row['description'];
$image_name = $row['image_name'];
$image_id = $row['image_id'];
$random_directory = $row['random_direc'];
$date = date('Y-m-d');
$image_info = "http://localhost/splindr_2.0/photos/$random_directory/$image_id";
echo "<div id=contentWrapper'>
<div id='photo'>
<div id='actual_image'>
<img src='$image_info'>
</div>
<div id='like_system'><button type='button' class='button' name='button'>Like</button></div>
<div id='info_wrapper'>
<div id='info_header'>Title: $title   By: $username   Date: $date</div>
<div id='description'>$description</div>
</div>
</div>
</div>";//end contentWrapper
}
?>
</body>
</html>
Here is the liked_button.php :
<!doctype html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="liked_button.css">
</head>
<body>
<button type="button" id="button_pressed">Liked</button>
</body>
</html>
Upvotes: 0
Views: 176
Reputation: 795
Here's the basic idea:
$(document).ready(function(){
$(".button").click(function(){
var t=$(this);
$.ajax({url:"liked_button.php",success:function(result){
t.replaceWith("<button type='button' id='button_pressed'>Liked</button>")
}});
});
});
Your other issue is that you use id overly much. Replace all looped uses of id
(including in the code I gave you) with class
, or else your code won't work.
Upvotes: 1
Reputation: 36438
HTML IDs (such as your like_system
) must be unique. Your update selector is finding the first one every time.
Try something like:
$(".button").click(function(){
var clicked = $(this);
$.ajax({url:"liked_button.php",success:function(result){
clicked.closest('div').html(result);
}});
});
And either remove the like_system
ID, or replace it with a class if you need to style it, etc.
Upvotes: 0