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>
Related
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??
I've made a popup message with auto-refresh function, so every few minutes the popup will appear to display the records. And it worked.
The following is the JavaScript code that auto refreshes:
$(document).ready(function() {
setInterval(function() {
$('#rtnotice').load('plugins/notice/n_notice_invoice.php').fadeIn("slow");
}, 5000)
});
code of n_notice_invoice.php
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#noticearea").hide();
});
});
</script>
<?php
try{
require_once "../../config/c_config.php";
$db = dbConn::getConnection();
$timestamp = $_REQUEST['term'];
$sqlck = $db->prepare("SELECT COUNT(id_notice_alert) as ttlinv FROM str_notice_alert WHERE date_alert > '$timestamp'");
$sqlck->execute();
$resck = $sqlck->fetch(PDO::FETCH_ASSOC);
if($resck['ttlinv'] == '0')
{}else{
?>
<div id="noticearea">
<div id="modal">
<div class="modal-content">
<div class="header">
<div id="circle" align="center"><h1><?php echo $resck['ttlinv'];?></h1></div><div class="titlenotice"><h1>NOTICE ALERT<?php echo $timestamp; ?></h1></div>
<div class="break"></div>
</div>
<div class="copy">
<p>
<table width="100%" class="gridtable">
<tr><th>No</th><th>Name</th><th>Status</th><th>Location</th><th>Date</th></tr>
<?php
$sqll = $db->prepare("SELECT * FROM str_notice_alert");
$sqll->execute();
while($resl = $sqll->fetch(PDO::FETCH_ASSOC)){
?>
<tr><td align="center"><?php echo $resl['id_notice_alert']; ?></td><td><?php echo $resl['alert_name']; ?></td><td align="center"><?php echo $resl['alert_status']; ?></td><td align="center"><?php echo $resl['alert_location']; ?></td><td><?php echo $resl['date_alert']; ?></td></tr>
<?php } ?>
</table>
</p>
</div>
<div class="cf footer">
<button id="hide" class="btn">Close</button>
</div>
</div>
<div class="overlay"></div>
</div></div>
<?php
$sqltrunc = $db->prepare("TRUNCATE TABLE str_notice_alert");
$sqltrunc->execute();
}$db = null;}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
?>
After a popup message is displayed, it will display the file n_notice_invoice.php existing records and also delete the records via queries available. In any appearances. But the question is, why the records are not updated / changed. uUnless I refresh the file directly n_notice_invoice.php, and then auto-refresh displays the most recent data.
$timestamp = $_REQUEST['term'];
should be updated each time you call the page. You should load the page with Ajax passing $timestamp as a parameter instead of just loading it.
To get what you need can I suggest you to use long polling? PHP long polling or even better with node.js. For php for example the "server" page:
$timeStart = time();
// Create connection
$con = mysqli_connect('localhost','root','','polldb');
// Check connection
if (mysqli_connect_errno($con))
die ('Failed to connect to MySQL: ' . mysqli_connect_error() );
// select where item is new
if(isset($_POST['timestamp'])){
$timestamp = $_POST['timestamp'];
}else{
// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
}
$sql = "SELECT * FROM `notification` WHERE timestamp > '$timestamp'";
$newData = false;
$notifications = array();
// loop while there is no new data and is running for less than 20 seconds
while(!$newData && (time()-$timeStart)<20){
// check for new data
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)){
$notifications[] = $row;
$newData = true;
}
// let the server rest for a while
usleep ( 500000 );
}
// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
mysqli_close($con);
// output
$data = array('notifications'=>$notifications,'timestamp'=>$timestamp);
echo json_encode($data);
exit;
and the client:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
pullNotification();
});
function pullNotification(timestamp){
var data = {};
if(typeof timestamp!='undefined')
data.timestamp = timestamp;
$.post('longpoll.php',data,function(msg){
var newData = '';
for(i in msg.notifications){
newData+=msg.notifications[i].message+'\n';
}
if(newData!='')
alert(newData);
pullNotification(msg.timestamp);
},'json');
}
</script>
This will check for database updates and will pop them up. Every 20 seconds it will renew the request. Obviously you have to adapt it to your needs.
I believie your issue comes from cached request (in Browser on in ajax itself)
please try to disable ajax caching :
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: "plugins/notice/n_notice_invoice.php",
cache: false
})
.done(function( data ) {
$('#rtnotice').html(data).fadeIn("slow");
});
}, 5000)
});
Im trying to get my PHP script called from AJAX (that is in my main php file).
Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/
The HTML source code shows only desk_box DIV being created (which is in my main.php). station_info DIV (being created in the display_station.php) is not there. How can I fix this? thanks in advance
Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call.
main.php with JQuery/AJAX part:
<div id="map_size" align="center">
<?php
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
?>
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$('.desk_box').each((function(){(this).click(function() {
var id = $(this).attr("data")
$("#station_info_"+id).toggle();
$.ajax({
url: 'station_info.php',
data: { 'id': id },
type: 'POST',
dataType: 'json',
success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}//end success
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
$html = '';
if($station_result->num_rows > 0){
while($row = $station_result->fetch_object()) {
$id = $row->coordinate_id;
$html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
}
}
else{
// no results - may want to do something with $html
$html = "no result given";
}
$station_result->free();
$conn->close();
echo $html;
?>
Why dont you filter the coordinate in the query? Like this:
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];
And in jquery code:
url: 'display_stationinfo.php?coordinate_id=' + id,
Let's start with your database connection, which should be on a separate secure page.
connect.php:
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Obviously, your host will not be 'host'.
Now main.php:
<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>This is Where Your Title Goes</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='main.js'></script>
<link rel='stylesheet' type='text/css' href='main.css' />
</head>
<body>
<div id='map_container'>
<div id='map_size'>
</div>
</div>
</body>
</html>
Now for main.js:
//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
for(var i in d){
var di = d[i], x = di.x, y = di.y;
var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
left:x,
top:y
});
// HTML id, class, and name attributes cannot start with a number
$("<div class='desk_box' data='"+i+"'>id:"+i+'</div>').css({
left:x,
top:y
}).appendTo(ms).append(sti).click(function(){
var info = $(this).next();
$.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
// do stuff with r
info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
}, 'json');
});
}
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>
Now for main_init.php:
<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
include_once 'connect.php'; $db = db(); $json = array();
$q = $db->query("SELECT * FROM table WHERE"); // example only
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
}
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// could be a hack
}
?>
Here's what live_info.php might look like:
<?php
if(isset($_POST['station_id'])){
include_once 'connect.php'; $db = db(); $json = array();
// example only - you will only get one `$row` if query is done specific, so while loop is not needed
$q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
if($q->num_rows > 0){
$row = $q->fetch_object();
// it's okay to overwrite array in this case
$json = array('love' => $row->love, 'hate' => $row->hate);
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// may be a hack
}
?>
I am using a joomla module i would like to modify to auto load the default list of results.
currently, when the page loads no result is shown. If all search fields are empty and the user clicks the search button, the page will load all data. If information in placed in the search fields, the results will be broken down to match what was typed in.
I want the page to auto load all data when the page loads without the user clicking search.
How do i achieve this?
I believe the module uses ajax and i believe the info that affects this is below:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/html');
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
ini_set("display_errors", "On");
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING);
$my_path = dirname(__FILE__);
$my_path = explode(DS.'modules',$my_path);
$my_path = $my_path[0];
if (file_exists($my_path . '/defines.php')) {
include_once $my_path . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', $my_path);
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();
///////////////////////////////////////////////////////////////////////////////////////////////
$name = $_GET['name'];
$value = mb_strtolower($_GET['value']);
$next = mb_strtolower($_GET['next']);
$db = JFactory::getDBO();
$query = "SELECT * FROM #__k2_extra_fields WHERE published = 1";
$db->setQuery($query);
$results = $db->loadObjectList();
$extra_val = '';
$extra_id = 0;
foreach($results as $result) {
if(trim(mb_strtolower($result->name)) == trim($value) . " " . trim($next) || trim(mb_strtolower($result->name)) == trim($next) . " " . trim($value)) {
$extra_val = $result->value;
$extra_id = $result->id;
break;
}
}
require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
$json = new Services_JSON;
$extra_val = $json->decode($extra_val);
if($extra_val != '') {
foreach($extra_val as $val) {
echo "<option>" . $val->name . "</option>";
}
echo "<option>".$extra_id."</option>";
}
?>
Please help!
to auto load search result we must need to store search query in session variable,
http://docs.joomla.org/How_to_use_user_state_variables
http://docs.joomla.org/API15:JApplication/getUserStateFromRequest
This are the links which will describe very well about how to manage request variable in session, so there is no variable in request it will get value from the session.
try to use something like this
<html>
<head>
<script>
function myFunction()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
then you can easily change myFunction to trigger your search on click event
<script>
function myFunction()
{
document.getElementById('YOUR-BUTTON-ID').onclick();
}
</script>
I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?