I have this site that show users who i can follow or not. its working without ajax but it get to reload on every button click.
I added ajax but it only stores the first following_id of the user displayed first into the database and nothing more. and its not right at all. having a long list of users and only one gets inserted into the database.
However, if i click on about 2 or more users to follow it inserts 2 or more rows of 1 following_id instead of 2 or more rows of different following_id been clicked.
Thanks in advance.
my ajax script
$(document).ready(function() {
$(".followUser").click(function(e) {
e.preventDefault();
var form = $('#userAction').serialize();
var action = 'instant_follow.php';
$.post(action, form, function(data){
//result goes here...
});
});
$('button#followResult').live('click', function(e){
e.preventDefault();
$button = $(this);
if($button.hasClass('unfollow')){
$button.removeClass('unfollow');
$button.text('follow');
$button.addClass('follow');
} else {
$button.addClass('unfollow');
$button.text('unfollow');
}
});
});
my php select form same page with my ajax script
$user = "1";
$stmt = $mysqli->prepare("SELECT * FROM site_users AS s LEFT JOIN site_follows AS f ON (f.following_id = s.user_id AND f.follower_id = ?) WHERE s.user_id != ? AND f.follow_id IS NULL ORDER BY RAND() LIMIT 7");
$stmt->bind_param("ii", $user, $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '
<form id="userAction" action="" method="post">
<p>'.$row["username"].'</p>
<button class="followUser" id="followResult">follow</button>
<input type="hidden" name="following_id" value="'.$row["user_id"].'">
</form>
';
}
} else {
echo "no user found...";
}
My php insert query on a different page
//user id which is 1
$user = "1";
$following_id = $_POST["following_id"];
$stmt = $mysqli->prepare("INSERT INTO site_follows (following_id, follower_id) VALUES (?, ?)");
$stmt->bind_param("ii", $following_id, $user);
$stmt->execute();
$stmt->close();