Currently I'm trying to make a Like Button with counter for my website. The issue I'm having, is that I'm not quite versed in javascript and AJAX, and do not know how to correctly write the AJAX Request.
The Ajax request does work, and does add the like (also removal works too) but I have to refresh the page, if I want to click that same like or dislike again. I can't keep clicking to like and unlike. (Hopefully that makes sense).
Here is my Jquery
$(document).ready(function(){
$('.post-add-icon').on('click', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/addlike.php',
type: 'post',
data: {
'likes': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
});
</script>
<script>
$(document).ready(function(){
// when the user clicks on unlike
$('.post-add-icon-active').on('click', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/removelike.php',
type: 'post',
data: {
'unliked': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
});
Here is addlike.php
require_once("../../config/db.php");
include_once("../classes/user.php");
include_once('../classes/posts/likes.php');
include_once('../classes/posts/comments.php');
include_once('../classes/posts/shares.php');
if(isset($_POST['likes'])) {
$id_post = $_POST['id_post'];
$id_user = $_SESSION['id_user'];
$likeTotal = mysqli_query($conn, "SELECT * FROM likes where id_post='$id_post'");
$likeTotalResult = mysqli_num_rows($likeTotal);
$likeTotalPerUser = mysqli_query($conn, "SELECT * FROM likes WHERE id_user='$id_user' AND id_post='$id_post'");
$likeTotalPerUserResult = mysqli_num_rows($likeTotalPerUser);
if($likeTotalPerUserResult > 0) {
$likes = new Likes($conn, $id_user);
$likes->loadLikes($id_post, $id_user);
$likesPictures = new Likes($conn, $id_user);
$likesPictures->loadLikerPictureArray($id_post, $id_user);
$staticCommentCountDisplay = New Comments($conn, $_SESSION[id_user]);
$staticCommentCountDisplay->DisplayCommentsTotal($id_post);
$staticShareCountDisplay = New Shares($conn, $_SESSION[id_user]);
$staticShareCountDisplay->DisplayShares($id_post);
exit();
} else {
mysqli_query($conn, "INSERT INTO likes (id_user, id_post, liked) VALUES ('$id_user', '$id_post', '1')");
$likes = new Likes($conn, $id_user);
$likes->loadLikes($id_post, $id_user);
$likesPictures = new Likes($conn, $id_user);
$likesPictures->loadLikerPictureArray($id_post, $id_user);
$staticCommentCountDisplay = New Comments($conn, $_SESSION[id_user]);
$staticCommentCountDisplay->DisplayCommentsTotal($id_post);
$staticShareCountDisplay = New Shares($conn, $_SESSION[id_user]);
$staticShareCountDisplay->DisplayShares($id_post);
exit();
}
}
This is the response of booth addlike and remove like.
if(mysqli_num_rows($hasUserLiked) > 0){
echo $likeEcho = '<div class="post-additional-info inline-items" id="likeUpdate-'. $id_post .'">
<span id="likeUpdate'. $id_post .'"><a style="cursor:pointer" class="post-add-icon-active inline-items" id="' .$id_post. '" data-id="' .$id_post. '">
<svg class="olymp-heart-icon">
<use xlink:href="svg-icons/sprites/icons.svg#olymp-heart-icon"></use>
</svg>
<span class="likes_count" id="' .$id_post. '">' .$totalLikes. '</span>
</a>
</span>';
} else {
echo $likeEcho = '<div class="post-additional-info inline-items" id="likeUpdate-' . $id_post . '">
<span id="likeUpdate'. $id_post .'"><a style="cursor:pointer" class="post-add-icon inline-items" id="' .$id_post. '" data-id="' .$id_post. '">
<svg class="olymp-heart-icon">
<use xlink:href="svg-icons/sprites/icons.svg#olymp-heart-icon"></use>
</svg>
<span class="likes_count" id="' .$id_post. '">' .$totalLikes. '</span>
</a>
</span>';
}
}
And lastly, here is my script toggle that is at the beginning of my post loop.
<script>
function toggle<?php echo $row['id_post']; ?>() {
var element = document.getElementById("toggleComment<?php echo $row['id_post'];?>");
if (element.style.display == "block")
element.style.display = "none";
else
element.style.display = "block";
}
</script>
Hopefully that is enough information. Like I was originally saying, if the user clicks the like button once, it displays the correct corresponding response. But if the user then decides to click that same button again(it's displayed new because of the response), it does nothing. Does the jquery toggle need to reload with the response?
I believe lies in fact that you send this:
'likes':'1'
this means that you always set likes to +1.
You should not send the number of likes at all. You should just send something like 'like', and your backend should do something like
previousNumberOfLikes++ // increment by 1.
You should never accept this kind of value from frontend, because it can be easily manipulated.
Best,
Edit:
I might be mistaken. You are returning totalLikes. This might be the issue. If you always send totalLikes without incrementing it, it will never change. Maybe look into this.
You're generating fresh post-add-iconso its not here on $(document).ready(), try it without replacing like icon
I think you need to unbind the event, follow the offical jquery website :
https://api.jquery.com/die/
You have to write document.ready function only once , not multiple time .
put all functions inside document.ready like below :
<script>
$(document).ready(function(){
$('.post-add-icon').on('click', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/addlike.php',
type: 'post',
data: {
'likes': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
// when the user clicks on unlike
$('.post-add-icon-active').on('click', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/removelike.php',
type: 'post',
data: {
'unliked': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
});
</script>
Try this!
<script>
$(document).ready(function(){
$('body').on('click','.post-add-icon', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/addlike.php',
type: 'post',
data: {
'likes': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
// when the user clicks on unlike
$('body').on('click','.post-add-icon-active', function(){
var id_post = $(this).data('id');
$post = $(this);
$.ajax({
url: 'includes/handlers/removelike.php',
type: 'post',
data: {
'unliked': 1,
'id_post': id_post
},
success: function(response){
$('#likeUpdate-'+id_post).replaceWith(response);
}
});
});
});
Related
I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';
I have a fontawesome icon in my HTML as a button and i'd like to use javascript and trigger it AJAX style
<i id="heart" class="jam jam-heart-f"></i> Like
Here is the attempt at javascript to trigger it - but I dont get any errors to follow up on. I try to post the like attempt to a PHP page like.php to add the link to a database.
$(document).ready(function()
{
$('body').on("click",'#heart',function()
{
var videoId = "<?php echo $video_id; ?>";
var A=$(this).attr("id");
var B=A.split("like");
var messageID=B[1];
var C=parseInt($("#likeCount"+messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {videoId: videoId},
cache: false,
success: function(result){
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
}
});
I dont think #heart seems to be triggered in JS by the id="heart" with the font awesome icon. Any ideas how I can rig this together
You forgot to add closing parenthesis and semicolon for your $('body').on... statement
Try this:
$(document).ready(function()
{
$('body').on("click",'#heart',function()
{
var videoId = "<?php echo $video_id; ?>";
var A=$(this).attr("id");
var B=A.split("like");
var messageID=B[1];
var C=parseInt($("#likeCount"+messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {videoId: videoId},
cache: false,
success: function(result){
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
});
});
Your code triggers the post-request correctly, but you are not closing your functions and scopes correctly.
I tried it out here:
http://jsfiddle.net/4cohrz5p/
And code to keep stackoverflow happy:
$(document).ready(function() {
$('body').on("click", '#heart', function() {
var videoId = "<?php echo $video_id; ?>";
var A = $(this).attr("id");
var B = A.split("like");
var messageID = B[1];
var C = parseInt($("#likeCount" + messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {
videoId: videoId
},
cache: false,
success: function(result) {
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
});
});
Besides, the javascript console shows Uncaught SyntaxError: missing ) after argument list for your code. And you open the network-tab when you click the heart to see outgoing requests and can inspect them to see that they send the correct data (and the response too!).
Any decent js editor would have shown this error before even running the code. Try VS Code. Free and lightweight and pretty great overall.
(If my english is bad I'm from pewdiepieland)
I have a problem that itch the hell out of me.
I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.
If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").
The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")
Do I have to reload the javascriptfile or anything else, or what do I need to do?
Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...
Best Wishes and Merry Christmas!
UPDATE << with Simplyfied code:
HTML/PHP
<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
<input type="file" name="img">
<input type="text" name="imgtxt">
<input type="submit" name="gallery-submit" value="Add Image">
</form>
<div id="gallery_content">
<?php
$result = mysqli_query($link, "SELECT * FROM gallery");
$count = 1;
while($row = mysqli_fetch_array($result)) {
$filename = $row['filename'];
$imgtxt = $row['imgtxt'];
$id = $row['id'];
echo '<div>';
echo '<img src="gallery/' . $filename . '">';
echo '<form id="editimg' . $count . '" role="form" method="POST">';
echo '<input type="text" name="imgtxt">';
echo '<input type="hidden" name="id">';
echo '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
echo '</form>';
echo '<button class="delete_img" value="' . $id . '">Delete</button>';
echo '</div>;
}
?>
</div>
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
$('.edit_img').click(function(e) {
e.precentDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
}
}
});
I don't think you need to see my process-file. Any clues?
Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});
See Here
Your problem is that you only hook up the .click() listeners once on "document ready".
When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:
$(document).ready(function() {
var setupGalleryEventListeners = function () {
$('.edit_img').click(function(e) {
e.preventDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
};
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
setupGalleryEventListeners(); // Setup initial event listeners on page load
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
}
}
});
Below is a piece of code that is placed inside for loop
for( some condition will go here )
{
echo "<td>
<a href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
</td>";
}
On clicking over it the user gets directed to event.php page and along with it, event_id and action parameters are also carried forward,
but instead of this
i wish to call event.php page to the first page through ajax for this i tried this
<script>
function chk()
{
$.ajax({
type:"post",
url: "event.php",
data:dataString,
cache:false,
success: function(html)
{
$('#msg').html(html);
}
}) ;
return false;
}
</script>
echo
"<td>
<a onclick='return chk()'>". ($i - $startday + 1) . "</a>
</td>";
but its not working, and i also wish yo carry forward event_id and action parameters through ajax to event.php page on every click, can anyone tell how this can be done
Here is what you can do
<a href="#" class="myclass" data-id="'.$someID.'" data-action="'.$someAction.'">
and js will be
$(".myclass").on("click", function(){
var id = $(this).data("id");
var action = $(this).data("action");
$.ajax({
type : "post",
url : "event.php",
data : {
"id":id,
"action":action
},
cache : false,
success : function(html)
{
$('#msg').html(html);
}
});
});
It should be like this
$.ajax({
type : "post",
url : "event.php",
data : {
"event_id":"-id of the event-",
"action":"-0action paramter-"
},
cache : false,
success : function(html)
{
$('#msg').html(html);
}
});
Build your loop adding a class:
echo "<td>
<a class='anEvent' href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
</td>";
Then use:
<script type="text/javascript">
$('.anEvent').on('click',function(e){
e.preventDefault();
$('#msg').load($(this).attr('href'));
})
</script>
You can use data attributes and $.post request, and better if you can avoid the inline-events and give your link an identifier (class ajax-link in my example because your code will be created from a loop so we don't have to use id since id should be unique in same document) then you can use it to attach click event to the a tag, check the following example :
PHP :
"<td>
<a class='ajax-link' data-event-id=".$datee2." data-action='Details'>". ($i - $startday + 1) . "</a>
</td>";
JS :
$('body').on('click', '.ajax-link', function(e){
e.preventDefault();
var url = $(this).data('action');
var event_id = $(this).data('event-id');
$.post(url, {event_id: event_id, action: action},
function(html)
{
$('#msg').html(html);
}
});
})
Hope this helps.
The problem is you are clicking the link which starts loading event.php.
You should use event.preventDefault() to avoid default action in chk() function.
function chk()
{
event.preventDefault();
$.ajax({
type:"post",
url: "event.php",
data:dataString,
cache:false,
success: function(html)
{
$('#msg').html(html);
}
});
return false;
}
When the user hovers over an image an information box comes up about that image, the information them changes inside the box as I move over another image but when I am over no images the information box stays. I can't close the information box (i.e. tooltips).
JS :
var id;
$(document).ready(function () {
$('a').mouseenter(function () {
//var id = $(this).parent().attr('myval');
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
});
$('a').onmouseleave(function () {
id = $(this).data.display = 'none';
}
});
How can I get the information box to disappear on mouse out?
I have tried multiple tests but the box doesn't even appear with them, the last one I tried is in the code above.
$('a').onmouseleave(function () {
id = $(this).data.display = 'none';
}
I am only starting out with javascript, jquery etc. in the last year.
Thank you in advance!!
Here is the php.
<div class="thumbnails">
<?php
$query = mysqli_query($connection, "select * from portfolio");
print "<ul>";
while ($row = mysqli_fetch_assoc($query)) {print "<li><img onClick=preview.src=" . $row['image'] . "name=" . $row['folio_id'] . "src={$row['image']}></td></li>";
}
print "</ul>";
?>
</div>
<!--Folio Information-->
<div id="fillFolio">Project Information</div>
I'm not sure, but try to use :
$('a').onmouseleave(function () {
$("#fillFolio").empty();
}
Hope this helps.
$("a").hover(function(){
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
}, function(){
//im not sure u want to hide or want to just clear your question not clear
$("#fillFolio").empty();
$("#fillFolio").hide();
});
Why not use jQuery hover = (mouseenter + mouseleave)
<script type="text/javascript">
var id;
$(document).ready(function () {
$('a').hover(function () {
//var id = $(this).parent().attr('myval');
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
,function () {
id = $(this).empty();
});
</script>