Why does ajax only work on the newest post? - php

I'm creating a social media site with php & mysqli. On the index page all post are loaded using a while loop and on the profile page that specific users post are loaded the same way. I have the like button hooked to ajax so you can like without refresh but it only works on the latest post.
The inside the while loop I have include('post.php') and this is what is in there.
<div class="post_options" id="post_options">
<div class="op_container like<?php echo $row['id'] ?>">
<i class="fa-regular fa-heart"></i> Like
</div>
<div class="op_container">
<i class="fa-regular fa-comment"></i> Comment
</div>
<div class="op_container">
<i class="fa-solid fa-share"></i> Share
</div>
</div>
</div>
<script>
const button = document.querySelector(".post_options .like<?php echo $row['id'] ?>")
button.onclick = () => {
let xhr = new XMLHttpRequest();
xhr.open("GET", "db/like_unlike.php?userid=<?php echo $_SESSION['id'] ?>&contentid=<?php echo $row['id'] ?>", true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
button.classList.toggle("active")
}
}
}
xhr.send();
}
</script>

What i understand from your code is that your script is outside the while loop. Hence it is taking the last value from your loop as the $row variable will store latest value.
You can add data attribute to your post div and then get that value on button click
<div class="post_options" id="post_options" data-id="<?php echo $row['id'] ?>">
<div class="op_container like<?php echo $row['id'] ?>">
<i class="fa-regular fa-heart"></i> Like
</div>
<div class="op_container">
<i class="fa-regular fa-comment"></i> Comment
</div>
<div class="op_container">
<i class="fa-solid fa-share"></i> Share
</div>
</div>
<script>
const button = document.querySelector(".post_options")
button.onclick = () => {
var contentid = $(this).data('id');
let xhr = new XMLHttpRequest();
xhr.open("GET", "db/like_unlike.php?userid=<?php echo $_SESSION['id'] ?>&contentid="+contentid, true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
button.classList.toggle("active")
}
}
}
xhr.send();
}
</script>

Related

Change class toggle to multiple span element with Jquery

I need to change the class of a span child that uses a toggle when I click on one of the browser rows.
But it only works when there is a single row, when there are several rows it does not find the span and it does not work.
I also tried to use the href to select the correct span, but I don't know how to use it in the JQuery code
<div>
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#01" class='btn btn-default' title='Ver pagos'>
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
<div>
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#02" class='btn btn-default' title='Ver pagos'>
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
jQuery(function($) {
$('#menu-toggle').on('click', function() {
var $el = $(this),
textNode = this.lastChild;
var $href = $(this).attr('href');
var $href = $href.substring(1);
$el.find('span').toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});
});```
Try this
var el = 2
for(var i=0; i<el.length; i++) {
document.getElementsByClassName("glyphicon").find('span').toggleClass('glyphicon-
chevron-down glyphicon-chevron-up');
}
Finally I simplified the code so I commented the span and then call with the function onclick CambiaClass, using a class data1, data 2 ... dataN (to identify the item) and now is working fine.
Thanks for your help Rahul!!!
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#<?php echo $id_item; ?>"
class='btn btn-default glyphicon glyphicon-chevron-down <?php echo 'dato'.$id_item; ?>'
title='Ver pagos' onclick="CambiaClass('<?php echo 'dato'.$id_item; ?>')">
<!-- span class="glyphicon glyphicon-chevron-down"></span -->
</a>
//Jquery
<script type="text/javascript">
function CambiaClass(idclass) {
$("[class*='"+ idclass+"']").toggleClass('glyphicon glyphicon-chevron-down').toggleClass('glyphicon glyphicon-chevron-up');
}
</script>

How to prevent Jquery script loading twice in ajax call or submit JQuery Function to Ajax Called Page

Hi guys i got a problem with my Code. I load new Page Content on click of Button and got a JQuery Function with onclick which changes a love or like count on Page. If i dont include the JQuery Function into the Ajax loaded page it doesn`t work but if i do he acts twice the function any idea how to fix this or solutions?
This is the JQuery Script from page:
$(".toggle").on("click", function(e) {
$('.alert-box').hide();
$( '.alert-box' ).remove();
var $this = $(this);
var $lovecount = $this.closest("div").find(".lovecount");
if ($(e.target).hasClass('love')) {
//alert('Liebe genommen');
var val = +$lovecount.text() + (this.checked ? -1 : -1);
$(e.target).prop( "checked", false );
} else {
//alert('Liebe gegeben');
var val = +$lovecount.text() + (this.checked ? 1 : 1);
$(e.target).prop( "checked", true );
};
//var val = +$lovecount.text() + (this.checked ? 1 : -1);
$lovecount.text(val)
$('.alert-box').toggle(!this.checked);
$(this).toggleClass("love");
var postid = $this.attr("data-post");
var userid = $this.attr("data-userid");
dataString = 'userid=' + userid + '&postid=' + postid;
// Are you not supposed to send the new value to the server?
$.ajax({
type: 'POST',
url: 'inc/give-love.php',
data: dataString,
success: function(response) {
$('<div class="alert-box success">'+response+'</div>').prependTo('body').delay(3000).fadeOut(1000, function() {
$('.alert-box').hide();
$( '.alert-box' ).remove();
});
}
})
})
with this i change and toggle input from this HTML Code Structure.
<!-- POST ITEM START -->
<div class="post-item">
<div class="post-asset image">
<img src="uploads/<?php echo $row['picture']; ?>">
</div>
<div class="post-header">
<h3 class="post-title"><?php echo $row['title']; ?></h3>
<span class="post-category">
<a class="favorite-button" href="#" data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>"><span class="favorite-button-icon fa fa-star-o"></span></a>
</span>
<span class="post-date font17"><i class="fa fa-clock-o"></i> <?php $timeago=get_timeago(strtotime($row['created'])); echo $timeago;?></span>
<span class="post-comments font17"><i class="fa fa-comments-o"></i> 1,3k Reaktionen</span>
</div>
<div class="post-footer">
<a href="#" class="post-author">
<span class="author-img"><img src="img/avatar.png"></span>
<span class="author-name">OnePost von<b><?php echo $row['poster']; ?></b></span>
</a>
<div class="post-extra">
<!--<div class="add-favorite" id="heart-container"><span class="lovecount">112</span><input data-post="123" data-user="Jessica Jones" type="checkbox" id="toggle" onclick="myFunction(this)" checked><div id="twitter-heart" class=""></div></input></div>-->
<div class="add-favorite" id="heart-container"><span class="lovecount"><?php echo $row['loves']; ?></span>
<!--<input data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>" type="checkbox" id="toggle" class="toggle love" onclick="myFunction(this)">-->
<?php
if($row['is_liked'] != 1){ ?>
<input data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>" type="checkbox" id="toggle" class="toggle">
<?}else{?>
<input data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>" type="checkbox" id="toggle" class="toggle love" checked="true">
<?php }?>
<div id="twitter-heart" class=""></div></input></div>
<div class="post-share"><i class="fa fa-share-alt"></i>
<div class="social-links">
<i class="fa fa-facebook"></i>
<i class="fa fa-twitter"></i>
<i class="fa fa-pinterest"></i>
<i class="fa fa-whatsapp"></i>
</div>
</div>
</div>
</div>
</div>
<!-- POST ITEM END -->
When i include the JQuery script in Ajax page it fires twice the function if not onclick is not working. How to prevent this or make it working the right way?
If you append any element after DOM has loaded, you need to use delegate(); selector.
$(document).ready(function(){
$("#div1").append('<button id="btn">Click</button>');
//You can use delegate() selector and when you click #btn its works.
$("body").delegate("#btn", "click", function(){
alert("Button has working!");
});
});

How to perform a query when a button is clicked in this legacy php web app?

I am totaly new in PHP and I have the following problem implementing a change request on a very old legacy web application (so I can't change the used logic).
I have this php file used to show a popup:
<?php
require_once("../../../common/lib.php");
require_once("../../../common/define.php");
if(isset($_POST['id']) && isset($_SESSION['user']['id'])){
$id_booking = (int)$_POST['id'];
if(is_numeric($id_booking)){ ?>
<script>
function printElem(elem){
var popup = window.open('', 'print', 'height=800,width=600');
popup.document.write('<html><head><title>'+document.title+'</title><link rel="stylesheet" href="<?php echo getFromTemplate("css/print.css"); ?>"/></head><body>'+document.getElementById(elem).innerHTML+'</body></html>');
setInterval(function(){
popup.document.close();
popup.focus();
popup.print();
popup.close();
}, 100);
return true;
}
</script>
<div class="white-popup-block" id="popup-booking-<?php echo $id_booking; ?>">
<h2><?php echo $texts['CANCEL_BOOKING'] ?></h2>
<p>Sei veramente sicuro di voler cancellare la prenotazione?</p>
<?php echo $id_booking; ?>
<a href="#" class="btn btn-primary sendAjaxForm" data-action="/perform_query">
<i class="fa fa-power-off"></i>
Conferma
</a>
<?php
$result_remove_booking = $db->query("UPDATE pm_booking SET status= ".$id_booking);
?>
</div>
<?php
}
?>
<?php
}
?>
As you can see it contains a confirmation "button", this one:
<a href="#" class="btn btn-primary sendAjaxForm" data-action="/perform_query">
<i class="fa fa-power-off"></i>
Conferma
</a>
I want implement the feature that when this button is clicked the following defined query is perfromed, this one:
<?php
$result_remove_booking = $db->query("UPDATE pm_booking SET status= ".$id_booking);
?>
After that this operation is executed the popup have to be closed.
How can I correctly perform my query when this button is clicked?

How to get new session value after some time using PHP

I need to get the new session value after some second using PHP. My code is below.
<button class="btn nextbtnbgdiv open2" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content">
<?php
$cat_id= $_SESSION['cid'];
?>
</div>
</div>
Here when user is clicking on next button the div section is opening and the the value is fetching from session. Here i need after some second always the updated $_SESSION['cid'] will fetch at each time click on next button.
In order to fetch the updated $_SESSION['cid'] you will need to make a call to the server to return this value, you can do so by embedding the value into an element i.e.
Back-end (i.e. get_session.php):
<html>
<body>
<div id="session"><?= $_SESSION['cid'] ?></div>
</body>
</html>
Front-end:
<button class="btn nextbtnbgdiv open2" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content"><?php $cat_id= $_SESSION['cid']; ?></div>
</div>
<script>
jQuery(function($) {
$(document).on( 'click', '.nextbtnbgdiv', function() {
$('.fyndspacecategory .nano-content').load('/get_session.php', '#session');
});
});
</script>
Or you could use a header within a page to access $_SESSION['cid'].
<?php
if ( isset( $_GET['get_session'] ) && $_GET['get_session'] ) {
header( 'X-Session: ' . $_SESSION['cid'] );
exit;
}
?>
<button class="btn nextbtnbgdiv open2" onclick="javascript:getSession();" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content" id="sessionId"><?php $cat_id= $_SESSION['cid']; ?></div>
</div>
<script>
function getSession() {
var request = new XMLHttpRequest();
request.onerror = function() { console.warn('An error occurred while checking session.'); };
request.open('HEAD', '?get_session=true', true);
request.onload = function() {
if ( request.getResponseHeader('X-Session') ) {
document.getElementById("sessionId").innerHTML = request.getResponseHeader('X-Session');
}
};
request.send();
}
</script>
This is not tested but should be enough to give you a start to complete your goal.

run javascript on separate ajax file

I have a question where I'd like to execute ReadMore/ReadLess javascript when button is clicked.
The clicked function is an ajax PostData() function .
The article or paragraph is located at a separate file called gethint.php
I dont get the javascript works in this scenario. However if I moved article or paragraph to the display.php , then it sucessfully run.
display.php
echo '<head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script></head>';
<input type="url" id="Url" name="Url" placeholder="http://example.com " class="form- control"/>
<span class="input-group-btn">
<button type="button" id="tx" class="btn green" onclick="PostData()"></button>
</span>
<div id="result"> </div>
<script>
function PostData() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var target = document.getElementById('result');
if (xhr.readyState === 4) {
if (xhr.status === 200 && xhr.status < 300) {
document.getElementById('result').innerHTML = xhr.responseText;
}
}
};
// 2. Define what to do when XHR feed you the response from the server - Start
var url = document.getElementById("Url").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'gethint.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Url=" + url);
// 3. Specify your action, location and Send to the server - End
}
</script>
//script for Read More /Read Less
<script>// Hide the extra content initially, using JS so that if JS is disabled, no problemo:
$(".read-more-content").addClass("hide");
$(".read-more-show, .read-more-hide").removeClass("hide");
// Set up the toggle effect:
$(".read-more-show").on("click", function(e) {
$(this).next(".read-more-content").removeClass("hide");
$(this).addClass("hide");
e.preventDefault();
});
$(".read-more-hide").on("click", function(e) {
$(this).parent(".read-more-content").addClass("hide");
var moreid=$(this).attr("more-id");
$(".read-more-show#"+moreid).removeClass("hide");
e.preventDefault();
}); </script>
gethint.php
<?php
if(isset($_POST['Url'])) {
$query = $_POST['Url'];
echo "<p> URL is " . $query . "</p>"
echo '<article>
<p>Egestas quos curabitur cum. <a class="read-more-show hide" href="#" id="1">Read More</a> <span class="read-more-content">Suspendisse! Rutrum cupidatat! <a class="read-more- hide hide" href="#" more-id="1">Read Less</a></span></p>
<p>Egestas mollitia quos natus. <a class="read-more-show hide" href="#" id="2">Read More</a> <span class="read-more-content">Suspendisse! Rutrum cupidatat! <a class="read-more- hide hide" href="#" more-id="2">Read Less</a></span></p>
<p>Egestas mollitia curabitur cum. <a class="read-more-show hide" href="#" id="3">Read More</a> <span class="read-more-content">Suspendisse! Rutrum conubia cupidatat! <a class="read-more-hide hide" href="#" more-id="3">Read Less</a></span></p>
</article> ' ;
}
You need to execute the code in your last script tag after the AJAX call has completed. Move it to a function and call the function. Given that you're using jQuery already, I'd recommend using jQuery.post and, in the callback, you can execute the code from your last script tag.

Categories