Please help to fix this issue with like counting.
i create a news feed like facebook using php mysql and ajax.
problem is that when i click on like button it prints like count from (this value) and showing to all, let say i have 5 posts and like current value for different posts are 100, 200 , 70 , 80 , 578. when I click on first post ajax success count 100+1 = 101 for first post and for all other post printting same 101 likes. now if i will go to 2nd post and its like value 200, ajax will show 200+1 =201 like. so after click on 2nd post all 5 posts like will show 201. its creating problem for me. I understand that after ajax success i mentioned to show the value to div class (.ajax_like_result), thats why its showing in every post, same result until i am not clicking on different post.
how to fix this so that when I click on any post it wil show only its real like value??
I try to change the DIV attribute id , instead of class then it only works for first post. other post totally not working. if i set div atribute to class then like is working but printing incorrectly as i mentioned above.
I have pasted below- html , php and ajax code . thanks for your help.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.ajax_like').on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(".ajax_like_result").html(data);
}
});
});
});
</script>
html :
<li class="ajax_like" type="submit" name="data-id" data-id="<?php echo $page;?>" value="<? echo $post_id;?>">
<div class= "ajax_like_result" ><?php print $likes;?></div>
</li>
like.php code :
<?php //user info start
session_start();
$conn=mysqli_connect("localhost", "u1068033_ab24", "ab#24", "u1068033_ab24");
mysqli_set_charset($conn,"utf8");
$id=$_SESSION['id'];
$get_post_id = $_POST['post_id'];
$page = $_POST['page'];
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
$likes=$row['likes'];
$sql="UPDATE $page SET `likes`=$likes+1 WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
echo $row['likes'];`enter code here`
?>
You should need some corrections on your jQuery
$(document).ready(function(){
$('.ajax_like').each( function(){
$(this).on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(this).find(".ajax_like_result").html(data);
}
});
});
})
});
you are writing the result to all HTML elements with the same class "ajax_like_result" when using this line:
$(".ajax_like_result").html(data);
you can use something such as:
$("li[data-id='"+page+"'] div.ajax_like_result").html(data);
Also better using native JavaScript and not jQuery, using document.querySelector
document.querySelector(`li[data-id='${page}'] div.ajax_like_result`).innerHTML = data;
and replace the jQuery AJAX with the native JavaScript fetch
example in one piece of code block with native JavaScript (no need for jQuery):
document.addEventListener("DOMContentLoaded", (event) => {
document.querySelectorAll('li[data-id]').forEach((elem)=>{
elem.addEventListener('click', event => {
const domElem = event.target;
const postId = domElem.getAttribute('value');
const page = domElem.getAttribute('data-id');
const data = {post_id:postId, page:page};
console.log({data});
fetch('like.php', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
const selector = `li[data-id='${page}'] div.ajax_like_result`;
document.querySelector(selector).innerHTML = data;
})
.catch((error) => {
console.error('Error:', error);
});
});
});
});
and better also to remove from the PHP code the '?>' as the PHP ends the script execution at the end and it will reduce some possible unwanted white spaces.
Related
I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)
ive been trying for hours to get this to work and havent moved a budge.
What im trying to do is send an url when a button is click, but without refreshing the page
php code of button:
echo 'Send';
jquery code:
<script type="text/javascript">
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('approve-button').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
$.ajax({
url: "votehandler.php", //This is the page where you will handle your SQL insert
type: "POST",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
</script>
votehandler.php:
<?php
$data = $_POST['id'];
mysql_query("UPDATE `link` SET `up_vote` = up_vote +1 WHERE `link_url` = '$data'");
?>
Ive removed all the error checks from votehandler.php to try to get any response but so far nothing.
any advice is welcome, trying to understand jquery/ajax.
Two problems with your code:
The jquery selector isn't working. Correct is: 'a[class="approve-button"]'
The code should being wrapped within the jquery ready() function to make sure that the DOM (with the links) has already been loaded before the javascript code executes.
Here comes a working example:
$(function() { // wrap inside the jquery ready() function
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('a[class="approve-button"]').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
$.ajax({
url: "votehandler.php", //This is the page where you will handle your SQL insert
type: "POST",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
});
I have this list of comments that i want to remove from database using AJAX, and fadeout from current view with Javascript.
I call this function removeComment() which sends ID of div to be removed to server ( ID is also row id in database )
The problem i have is, after i run the function first time, it stops working.
jquery code
function removeComment(PostId) {
var commentid = 'com' + PostId;
$(document).ready(function() {
$(commentid).fadeToggle('slow');
// send to php script
$.ajax({
type: 'POST',
cache: false,
url: 'actions/adminProcessor.php',
data: 'action=removeComment' + '&PostId=' + PostId,
success: function(done) {
alert(done);
}
});
}); // <-- Sorry, was missing a '}'
}
and below is the html of the comment list and how the functionis called
<div class="comments" id="com3">
<label><admin>UD</admin></label>Remove
<span>17/09/12</span>
<p>adfadfadfadf</p>
</div>
<div class="comments" id="com3">
<label><admin>UD</admin></label>Remove
<span>17/09/12</span>
<p>adfadfadfadf</p>
</div>
please i would like to know where i got it wrong
below is the php script
if($action == "removeComment"){
extract($_POST) ;
$query = "DELETE FROM comments WHERE id = '$cId'" ;
$result = mysql_query($query);
}
You should not wrap your behavior into a $(document).ready function. You should read more about what $(document).ready means. This code should work now:
function removeComment(PostId) {
var commentid = 'com' + cid;
var coms = document.getElementById(commentid);
$(coms).fadeToggle('slow');
$.ajax({
type: 'POST',
cache: false,
url: 'actions/adminProcessor.php',
data: 'action=removeComment' + '&PostId=' + PostId,
success: function (done) {
alert(done);
}
});
}
this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');
Am a noob so hope you can help!
I've got the following jquery code:
$("#single-home-container").html(post_id);
It then displays the value I want within the HTML on the page:
<div id="single-home-container"></div>
What I would like is to pass the value into a PHP variable to I can use the info in a MySQL query.
How do I do so? It's in WordPress so no separate files
Thanks
You can use jQuery.post() or jQuery.ajax().
Here some examples:
<script>
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
</script>
<script>
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
</script>
You'd need to use ajax. Something like this:
JQuery:
$('.locationID').click(function(){
var post_id = $(this).attr('rel'),
$container = $("#single-home-container");
old_html = $container.html();
$container.html('loading...');
$.ajax({
url : '/path/to/php/file.php',
data:{"post_id":post_id},
type: 'post',
dataType: 'json',
success: function(data){
$container.html(data.postBody);
},
error: function(data){
// possibly notify the user of the error
$container.html(old_html);
}
});
});
That assumes you have a field in your posts table called postBody
PHP
<?php
header('Content-type: application/json');
// $query_result = do mysql query with $_POST['post_id']
echo json_encode($query_result);
exit();
?>
That assumes that you want all the fields and you're returning all the fields, including postBody - and of course you have PHP 5.2.6+ or whatever version they added json_encode().