I'm making a following system. If the user clicks on the follow button an ajax function is triggerd. The ajax function sends data to the actions.php file and this file checks if there is data in the database. Based on this info the code inserts the follower or deletes it from the database. This works fine! But for example if one user starts following the other person and than refresh the page the buttons html changes back to follow.
I have tried to do the result in php but it didn't work out
ajax:
$(".toggleFollow").click(function() {
var id = $(this).attr("data-userId");
$.ajax({
type: "POST",
url: "actions.php?action=toggleFollow",
data: "userId=" + id,
success: function(result) {
if (result == "1") {
$("button[data-userId='" + id + "']").html('<span class="icon icon-add-user"></span> Follow');
} else if (result == "2") {
$("button[data-userId='" + id + "']").html('<span class="icon icon-remove-user"></span> Unfollow');
}
}
})
})
actions.php:
session_start();
require 'dbh.inc.php';
$id = $_SESSION['userId'];
$userId = $_POST['userId'];
if ($_GET['action'] == 'toggleFollow') {
$query = "SELECT * FROM isFollowing WHERE follower = ". mysqli_real_escape_string($conn, $_SESSION['userId'])." AND isFollowing = ". mysqli_real_escape_string($conn, $_POST['userId'])." LIMIT 1";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
mysqli_query($conn, "DELETE FROM isFollowing WHERE id = ". mysqli_real_escape_string($conn, $row['id'])." LIMIT 1");
echo "1";
} else {
mysqli_query($conn, "INSERT INTO isFollowing (follower, isFollowing) VALUES (". mysqli_real_escape_string($conn, $_SESSION['userId']).", ". mysqli_real_escape_string($conn, $_POST['userId']).")");
echo "2";
}
}
I expect that the follow/unfollow button doesn't change after an refresh! PS This is my first question on stackoverflow!