Button from a ajax post page doesnt work when clicked [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 1 year ago.
I have a commenting project that has a button id #see_more_comments inside my .user__comments__container div that is being outputted from a getcomments-afunc.php file via jquery post when the comment is more than 4. The file code of ajax.php is:
<?php
session_start();
include_once '../dbh-inc.php';
if (isset($_SESSION['userid'])) {
$jobsid = mysqli_real_escape_string($conn, $_POST['jid']);
$output = "";
$sql = "SELECT * FROM comments AS c INNER JOIN users AS u ON c.usersId = u.usersId WHERE c.jobsId = '$jobsid' ORDER BY c.cid DESC LIMIT 4;" ;
$result = mysqli_query($conn, $sql);
$commentcount = 3;
if (mysqli_num_rows($result) > $commentcount) {
while ($row = mysqli_fetch_assoc($result)) {
$usersid = $row['usersId'];
$commenterprofilepic = $row['usersProfilePic'];
$username = $row['usersName'];
$usersusername = $row['usersUsername'];
$commentDesc = $row['commentDesc'];
$commentDate = $row['commentDate'];
$output .= '<div class="user__comments">
<img src="profilepic/'.$commenterprofilepic.'" alt="'.$username.'\'s profile picture" class="profile__thumbnail" onclick="location.href=\'profile?uid='.$usersid.'\'">
<div class="comment__bubble">
<div class="comment__box">
<p class="username" onclick="location.href=\''.$usersusername.'\'">'.$username.'</p>
<p class="comment">'.nl2br($commentDesc).'</p>
</div>
<p class="date">'.$commentDate.'</p>
</div>
</div>';
}
$output .= '<div class="see__more__comments" id="see_more_comments">See more comments..</div>';
}
echo $output;
}
else {
header("../../dashboard.php");
exit();
}
Now, when it is outputted to my index.php via a jquery post call, it is registered and can be seen at the elements tab of my browser or DOM.
It is outputted via this jquery code:
setInterval(() => {
$.post('includes/ajax-func/getcomments-afunc.php', {
jid : pageId
}, function (response) {
$('.user__comments__container').html(response);
});
}, 10000
);
However, when I am clicking so that it will add 4 more comments to my .user__comments__container index.php. It doesnt work, I tried making a console.log for it but it hasnt outputted anything, this is the code for clicking the button:
$('#see_more_comments').click(function() {
commentCount = commentCount + 4;
$('.user__comments__container').load('includes/ajax-load/seemorecomments-aload.php' , {
jobsId : pageId,
newCommentCount : commentCount
});
console.log(commentCount);
});
And this is the seemorecomments-aload.php content:
<?php
session_start();
include_once '../dbh-inc.php';
$jobsid = $_POST['jobsId'];
$newcommentcount = $_POST['newCommentCount'];
$sql = "SELECT * FROM comments AS c INNER JOIN users AS u ON c.usersId = u.usersId WHERE c.jobsId = '" . $jobsid . "' ORDER BY c.cid DESC LIMIT $newcommentcount;" ;
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$usersid = $row['usersId'];
$commenterprofilepic = $row['usersProfilePic'];
$username = $row['usersName'];
$usersusername = $row['usersUsername'];
$commentDesc = $row['commentDesc'];
$commentDate = $row['commentDate'];
echo '<div class="user__comments">
<img src="profilepic/'.$commenterprofilepic.'" alt="'.$username.'\'s profile picture" class="profile__thumbnail" onclick="location.href=\''.$usersusername.'\'">
<div class="comment__bubble">
<div class="comment__box">
<div class="username" onclick="location.href=\''.$usersusername.'\'">'.$username.'</div>
<div class="comment">'.$commentDesc.'</div>
</div>
<div class="date">'.$commentDate.'</div>
</div>
</div>';
}
Before all of this, I have all getcomments-afunc.php content without the $output, $output is replaced by echo, inside my index.php .user__comments__container and it worked just fine..
However, when I decided to add jquery to it so that I wont need to reload the wholepage, my purpose of letting the .user__coments__container reload itself worked but the button doesnt work anymore.
Any help? thank you!! :(

Change the line
$('#see_more_comments').click(function() {
To
$(document).on("click","#see_more_comments",function() {

Thanks Mr. Majid Ali and Mr. Swati,
It worked!! by using $(document).on("click","#see_more_comments",function() {
May I know why $('#name').click doesnt work sometimes??

Related

Using span text in where clause in php

This div act as a button. Whenever I click one, the page goes to the page name "teacherinfo.php". The "Sample" text is used as the name of the teacher. The problem is when I click the "Sample2" the Sample text appear on the "teacherinfo.php" page.
Here is the script for going to "teacherinfo.php":
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<div class="announcementSlider" id="click">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</div>';
}
?>
<script type="text/javascript">
var a = document.getElementsByClassName("announcementSlider");
for (i=0; i<a.length; i++) {
a[i].onclick = function () {
location.href = "teacherinfo.php";
};
}
</script>
Code for displaying the text in "teacherinfo.php":
<div class="leftForm hide-on-med-and-down">
<img src="pictures/default-avatar-250x250.png">
<p class="name"><?php echo $name3; ?></p>
<p class="section"><?php echo $grade3; ?>-<?php echo $section; ?></p>
</div>
Code for retrieving data in database:
$sql3 = mysqli_query($db,"select * from teacherinfo");
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];
I want to use the "'.$row['LastName'].'" as a where clause in mysqli_query($db,"select * from teacherinfo"). How can I do that? or is there another solution to this issue?
First of all, I don't understand why you use javascript when you can use simple a tag with correct href:
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<a class="announcementSlider" href="teacherinfo.php?id=' . $row['id'] . '">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</a>';
}
?>
Here, I suppose that every teacher in your mysql-table has some unique id field.
On teacherinfo.php you access id as $_GET['id'] and create a query like (here I skip security part, but $_GET['id'] can be forged and therefore contain some insecure data, you have to check it):
sql3 = mysqli_query($db,"select * from teacherinfo where id = " . $_GET['id']);
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];

PHP and AJAX Updating notifications in real time

Currently having some trouble with an AJAX call. It is meant to display notifications in real time, with reference to an external php file. When I tested the php inside index.php it worked fine, but for some reason it doesn't work when I try to call the code via ajax. Anyone know what I'm doing wrong?
Edit: Solved by adding session_start(); at top of file, and also by using .class instead of #id in ajax call.
In notif_follow.php:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id=:rid ORDER BY id DESC LIMIT 5");
$stmt->execute(array(":rid"=>$user_id));
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if($notifs !== false)
{
foreach($notifs as $notif)
{
$notification .= '
<li>
<div class="notifbox">
<strong>'.$notif['send_name'].'</strong><p> is now following you.</p>
<button class="button">Follow</button><button class="button">View Channel</button>
</div>
</li>
<li class="divider"></li>
';
}
}
else
{
$notification .= '<li>No Notifications Found</li>';
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification);
echo json_encode($notif_array);
?>
Ajax call in index.php:
<script type="text/javascript">
var timer;
timer = setInterval(function() {
$(document).ready(function(){
$.getJSON('notif_follow.php', function(data) {
$('#notifbox').html(data.notification);
});
});
}, 1 * 1000);
</script>

jQuery "Event Listener" not working with data coming from Database

I am pulling text from my database and inserting into a P TAG that has a class that serves as a handle for my listener, however when I click on the text, nothing happens the JavaScript does not react.
Website : http://fluentabc.com/edit.php
Here is a Picture :
HTML
<p class="sec_text" id="sec_1" data-reveal-id="myModal">
<?php
$query = mysqli_query($con,"SELECT * FROM site_edit WHERE site_sec='MainTitle'");
while($qt = mysqli_fetch_array($query)){
echo $MainTitle = $qt['site_txt']; // <-- I WANT TO CLICK ON THIS TEXT
}
?>
</p>
JS
$(document.body).on('click', '.sec_text' ,function(){
var txt = $(this).text();
var sec_id = $(this).parent().attr('id');
$("#curEditing").html("Your Editing : " + sec_id);
$("#sec_edit_name").val(sec_id);
tinyMCE.activeEditor.setContent(txt);
});
Just update your html code 100% working:
Your output should be like this:
<p class="sec_text" id="sec_1" data-reveal-id="myModal">Learn English Today!</p>
Update HTML:
<p class="sec_text" id="sec_1" data-reveal-id="myModal">
<?php
$query = mysqli_query($con,"SELECT * FROM site_edit WHERE site_sec='MainTitle'");
while($qt = mysqli_fetch_array($query)){
echo $MainTitle = strip_tags($qt['site_txt']); // <-- I WANT TO CLICK ON THIS TEXT
}
?>
</p>
<div>
<?php
$query = mysqli_query($con,"SELECT * FROM site_edit WHERE site_sec='MainTitle'");
while($qt = mysqli_fetch_array($query)){
echo '<p class="sec_text" id="sec_1" data-reveal-id="myModal"'>.$qt['site_txt'].'</p>'; // <-- I WANT TO CLICK ON THIS TEXT
}
?>
</div>

Calling PHP file via AJAX, passing $_GET variable into MySQL query, then echoing into response

So I have this jQuery AJAX call that activates when I click on any of the divs with the class="username" attribute, which contains a user's username, like:
<div class="username">Sneaky</div>
Here's the jQuery AJAX call:
var usersName = '';
$('#chatContainer').delegate('div.username', 'click', function(e) {
usersName = $(this).text();
$.ajax({
method: 'GET',
url: 'profile_popup.php',
data: { usersName: usersName },
success: function(data) {
$("#profilePopup").show().offset({left:e.pageX,top:e.pageY}).html(data);
}
});
});
Here's the PHP file that it calls:
include 'MySQL_connect.php';
$name = mysql_real_escape_string($_GET['usersName']);
$sql = "SELECT chat_color FROM users WHERE username='$name'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$chatColor = $row["chat_color"];
$sql = "SELECT profile_pic FROM profiles WHERE username='$name'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$profilePic = $row["profile_pic"];
echo "<div style='color:$chatColor'>$name</div>
<img style='height:64px' src='../profile/profile_pictures/$profilePic'>";
My problem is that it returns with no error but without the MySQL database values, like so:
<div id="profilePopup">
<div style="color:"> Sneaky</div>
<img src="../profile/profile_pictures/" style="height:64px">
</div>
Any clues as to why this isn't working as intended? I've done quite a lot with jQuery, PHP and MySQL on this site and this seems like it should work correctly.
Don't bite me if I'm wrong, assuming all your SQL codes are correct, can you try
echo "<div style='color:" . $chatColor . "'>" . $name . "</div>
<img style='height:64px' src='../profile/profile_pictures/" . $profilePic . "'>";
-- EDIT --
Perhaps edit your PHP file to:
include 'MySQL_connect.php';
$name = $mysqli->real_escape_string($_GET['usersName']);
$sql = "SELECT `chat_color`, `profile_pic` FROM users LEFT JOIN profiles ON (`users`.`username` = `profiles`.`username`) WHERE `username` = '" . $name . "'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$chatColor = $row['chat_color'];
$profilePic = $row['profile_pic'];
echo "<div style='color:$chatColor'>$name</div>
<img style='height:64px' src='../profile/profile_pictures/$profilePic'>";
I figured it out. I did some testing, and after checking what the javascript "usersName" variable was set to, I noticed that there was a space at the beginning. I don't know why, or how it got there, but it was there. I just did a quick workaround in the PHP file as follows:
$name = mysql_real_escape_string($_GET['usersName']);
$name = ltrim($name," ");
This simply trims the whitespace from the beginning of the string. Thanks for all the help! :)
Try this.
PHP
$text='<div style="color:'.$chatColor.'">'.$name.'</div>
<img style="height:64px"src="../profile/profile_pictures/'.$profilePic .'">';
echo '{"item" :'.json_encode($text).'}';
AJAX
success: function(data) {
obj=$.parseJSON(data);
$("#profilePopup").show().offset({left:e.pageX,top:e.pageY}).html(obj.item);
}

Reload Script Accessed On Another Website

I'm trying to create a script that runs and updates real time(semi if needed) on another website.
The back bone of this is a php script which accesses a database on my server. From there it outputs some basic variable information.
So we're on the same page. This is the script itself.
Located on www.A.com-->
<?php
include "includes/db_conx.php";
// This block grabs the whole list for viewing
$sql = "SELECT * FROM pages ORDER BY id DESC";
$result = mysqli_query($db_conx,$sql);
$productCount = mysqli_num_rows($result);
if ($productCount > 0) {
$x=0;
while($row = mysqli_fetch_assoc($result)){
$id = $row["id"];
$url = $row["url"];
$status = $row["status"];
$headerCode = $row["headerCode"];
$bodyCode = $row["bodyCode"];
if($status == "Ready") {
$statClass = "greenBox";
}
if($status == "Live") {
$statClass = "yellowBox";
}
if ($status == "Hold")
$statClass = "blueBox";
$lastEdit = strftime("%b %d, %Y", strtotime($row["lastEdit"]));
$x++;
$bgChange = ($x%2 == 0)? '': 'blackRow';
$product_list .= "<div class='row noMargin $bgChange'><div class='boxMini idColDeveloper'>$id</div><div class='boxMini statusColDeveloper $statClass boldDiv twelveFont' style='margin:4px;'>$status</div><div class='boxMini urlColDeveloper'>$url</div><div class='boxMini' id='postDateDeveloper'>$lastEdit</div><div class='boxMini actionColDeveloper'><div style='float:left;'> <a href='bodyCodes_edit.php?pid=$id'>Edit</a></div><div style='float:left;margin-left:12px;'><a href='bodyCodes_creator.php?deleteid=$id'><img src='https://www..com/upload/images/delete-item.png' alt='delete' style='display:block;margin-left:auto;margin-right:auto;'/></a></div></div><div class='clear'></div></div>";
$list = $product_list;
}
}
echo ("document.getElementById('date-holder').innerHTML = '".addslashes($list)."';");
?>
On an entirely different website and server I'm using this code to display the information from my database at www.A.com:
Located on www.B.com-->
<script src="https://www..com/test/test.php"></script>
Is there any way to update this every second or less? So it's something of a real time output.

Categories