I have tried to make a real time chat, but i have a problem: setInterval (for checking for new messages) does not work :/...
This is my jQuery code
$(function(){
setInterval(function() {
$.ajax({
url: "./ajax/checknew.php",
success: function(data) {
$("#chMsgCont").append(data);
}
});
},1000);
$('#chMsgCont').load('./ajax/msg.php', function() {
var div = $('#chMsgCont');
var o = div.offset().top;
div.scrollTop( o + 12302012 );
});
});
My msg.php
<?php
include("../system/config.site.php");
$query = mysql_query("SELECT * FROM chat_msg ORDER BY timestamp ASC");
while($p = mysql_fetch_assoc($query)) {
$auth = mysql_fetch_assoc(mysql_query("SELECT * FROM chat_users WHERE id = '".$p['auth_id']."'"));
$update = mysql_query("UPDATE chat_msg SET new = 'no' WHERE id = '".$p['id']."'");
?>
<div class="chatMsg">
<p id="chatPMsg">
<span class="chatTime"><?php echo date("H:i", $p['timestamp']); ?></span>
<b><?php echo $auth['name']." ".$auth['surname']; ?></b><br />
<?php echo stripslashes($p['msg']); ?>
</p>
<p id="chatImg">
<img src="./images/thumb<?php echo $p['auth_id']; ?>.png" />
</p>
<div style="clear:both;"><!– –> </div>
</div>
<?php
}
?>
My checknew.php
<?php
include("../system/config.site.php");
$query = mysql_query("SELECT * FROM chat_msg WHERE new = 'yes' ORDER BY timestamp ASC");
if(mysql_num_rows($query) > 0) {
while($p = mysql_fetch_assoc($query)) {
$auth = mysql_fetch_assoc(mysql_query("SELECT * FROM chat_users WHERE id = '".$p['auth_id']."'"));
?>
<div class="chatMsg">
<p id="chatPMsg">
<span class="chatTime"><?php echo date("H:i", $p['timestamp']); ?></span>
<b><?php echo $auth['name']." ".$auth['surname']; ?></b><br />
<?php echo stripslashes($p['msg']); ?>
</p>
<p id="chatImg">
<img src="./images/thumb<?php echo $p['auth_id']; ?>.png" />
</p>
<div style="clear:both;"><!– –> </div>
</div>
<?php
}
} else {
echo "";
}
?>
setInterval refuses to append the results of the query :/, how is it possible?
May it must call window.setInterval() ?
Related
I'm currently doing a private chat (style messenger), and I got a problem..
I have a href a link which sends an ID using GET to another page, the thing is that on the other page I load a jquery script which again sends to another page, suddenly it no longer finds the ID GET, what should I do? I want to actualise the page (the messages) thanks (noted that I'm new, I'm not enough good to use ajax or something..)
message.php
message
<?php
// $allUsers = 'SELECT * FROM members WHERE name LIKE "%cc%" ORDER BY id DESC' / SEARCH MEMBERS
$allUsers = $dbh->query('SELECT * FROM members ORDER BY id DESC LIMIT 0, 5');
if ($allUsers->rowCount() > 0)
{
while ($user = $allUsers->fetch())
{
?>
<div id="s_un_main">
<div class="s_un_main_pun">
<img src="../images/avatar/<?php echo $user['avatar'];?>">
<p><?php echo $user['name']; ?></p>
</div>
<div class="s_un_main_pdeux">
<a class="private" target="_blank" href="private.php?id=<?php echo $user['id']; ?>">Message</a>
</div>
</div>
<?php
}
}
else
{
echo "<p>" . "Aucun utilisateur trouvé. " . "</p>";
}
?>
private.php
private
<div id="get_name">
<?php
// USERINFO
if (isset($_SESSION['id']) AND !empty($_SESSION['id']))
{
$getid = $_GET['id'];
$req = $dbh->prepare('SELECT * FROM members WHERE id = :getid');
$req->bindValue('getid', $getid);
$req->execute();
$userinfo = $req->fetch();
}
?>
<div>
<img id="img_header" width="50" src="../images/avatar/<?php echo $userinfo['avatar'];?>">
</div>
<?php echo "<p>" . $userinfo['name'] . "</p>"; ?>
</div>
<section id="zz">
<div id="show_msg">
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
</div>
</section>
<form id="private_form" method="POST" action="">
<textarea name="message"></textarea>
<input type="submit" name="send"></input>
</form>
<script>
setInterval('load_messages()', 1500);
function load_messages()
{
$('#zz').load('private_message.php');
}
</script>
private_message.php
error
<!-- DB -->
<?php include("../db/db.php"); ?>
<!-- DB -->
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
var_dump($getid);
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
var_dump($id) = not found
I have code for loading more content on button click. And I have another for loading on scroll. The code for the button loads fine. The code for scroll duplicates the new loaded content like 3 times. Both codes use the same php load file. All are listed below. What is wrong with the scroll code? All help is appreciated. FYI, I am not interested in Jquery infinite scroll, or any other plugin. Thanks!
LOAD ON CLICK WITH BUTTON
<!DOCTYPE html>
<html>
<head>
<title>Load More Button</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div>
<h2 align="center">Load More Button</h2>
<div style="height:10px;"></div>
<div id="load-content">
<?php
$lastid = '';
include('connection.php');
$query = mysqli_query($connection, "select * from transactions order by id asc limit 5");
while ($row = mysqli_fetch_array($query)) {
?>
<div>
<div>
<?php echo $row['id']; ?>
<br>
<?php echo $row['description']; ?>
<br>
<?php echo $row['promorefnum']; ?>
<br><br>
</div>
</div>
<?php
$lastid = $row['id'];
}
?>
<div id="remove">
<div style="height:10px;"></div>
<div>
<div>
<div id="load-more" data-id="<?php echo $lastid; ?>">Load More</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$(document).on('click', '#load-more', function() {
var lastid = $(this).data('id');
$('#load-more').html('Loading...');
$.ajax({
url: "load-data.php",
method: "POST",
data: {
lastid: lastid,
},
success: function(data) {
if (data != '') {
$('#remove').remove();
$('#load-content').append(data);
} else {
$('#load-more').html('End Of Data');
}
}
});
});
});
</script>
</body>
</html>
LOAD MORE ON SCROLL
<!DOCTYPE html>
<html>
<head>
<title>Load More Scroll</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div>
<h2 align="center">Load More Scroll</h2>
<div style="height:10px;"></div>
<div id="load-content">
<?php
$lastid = '';
include('connection.php');
$query = mysqli_query($connection, "select * from transactions order by id asc limit 11");
while ($row = mysqli_fetch_array($query)) {
?>
<div>
<div>
<?php echo $row['id']; ?>
<br>
<?php echo $row['description']; ?>
<br>
<?php echo $row['promorefnum']; ?>
<br><br>
</div>
</div>
<?php
$lastid = $row['id'];
}
?>
<div id="remove">
<div style="height:10px;"></div>
<div>
<div>
<div id="load-more" data-id="<?php echo $lastid; ?>"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
window.onscroll = function() {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2) {
var lastid = $('#load-more').data('id');
$('#load-more').html('Loading...');
$.ajax({
url: "load-data.php",
method: "POST",
data: {
lastid: lastid,
},
success: function(data) {
if (data != '') {
$('#remove').remove();
$('#load-content').append(data);
} else {
$('#load-more').html('End Of Data');
}
}
});
}
}
});
</script>
</body>
</html>
PHP CODE / LOAD FILE
<?php
sleep(1);
include('connection.php');
if (isset($_POST['lastid'])) {
$lastid = $_POST['lastid'];
$query = mysqli_query($connection, "select * from transactions where id > '$lastid' order by id asc limit 10");
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
?>
<div>
<?php echo $row['id']; ?>
<br>
<?php echo $row['description']; ?>
<br>
<?php echo $row['promorefnum']; ?>
<br><br>
</div>
<?php
$lastid = $row['id'];
}
?>
<div id="remove">
<div style="height:10px;"></div>
<div>
<div>
<div id="load-more" data-id="<?php echo $lastid; ?>">Load More</div>
</div>
</div>
</div>
<?php
}
}
?>
Try this check
<head>
<title>Load More Scroll</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div>
<h2 align="center">Load More Scroll</h2>
<div style="height:10px;"></div>
<div id="load-content">
<?php
$lastid = '';
include('connection.php');
$query = mysqli_query($connection, "select * from transactions order by id asc limit 11");
while ($row = mysqli_fetch_array($query)) {
?>
<div>
<div>
<?php echo $row['id']; ?>
<br>
<?php echo $row['description']; ?>
<br>
<?php echo $row['promorefnum']; ?>
<br><br>
</div>
</div>
<?php
$lastid = $row['id'];
}
?>
<div id="remove">
<div style="height:10px;"></div>
<div>
<div>
<div id="load-more" data-id="<?php echo $lastid; ?>"></div>
</div>
</div>
</div>
<span id="loading">Loading...</span>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#loading").hide();
window.onscroll = function() {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2) {
var lastid = $('#load-more').data('id');
if($("#loading").css('display') == 'none') {
$("#loading").show();
$.ajax({
url: "load-data.php",
method: "POST",
data: {
lastid: lastid,
},
success: function(data) {
if (data != '') {
$('#remove').remove();
$('#load-content').append(data);
$("#loading").hide();
} else {
$('#load-more').html('End Of Data');
}
}
});
}
}
}
});
</script>
</body>
</html>
I have the following script for showing posts and liking them, but if I like one post it likes all the posts on the page, I can't think of another way to do it, can anyone give me some advice?
<?php
if ($sort == 1){
$result = $conn->query("SELECT * FROM posts ORDER BY date DESC LIMIT 4 ");
}
elseif($sort == 2)
{
$result = $conn->query("SELECT * FROM posts WHERE date > NOW() - INTERVAL 24 HOUR ORDER BY likes DESC");
}
elseif($sort == 3)
{
$result = $conn->query("SELECT * FROM posts ORDER BY likes DESC");
}
if ($result->num_rows > 0) :
while($row = mysqli_fetch_assoc($result)) : ?>
<div class="card mb-4">
<img class="card-img-top" src="<?php echo $row['image1'] ?>" alt="Card image cap">
<div class="card-body">
<h2 class="card-title"><?php print title; ?></h2>
<p class="card-text"><?php print text; ?></p>
Read More →
</div>
<div class="card-footer text-muted">
Posted on <?php print $row['date'] ?> by
<?php print $row['author']; ?>
<?php
$id=$row['id'];
if($_POST['like']) {
$update = "UPDATE posts set `likes` = `likes`+1 where `id` ='$id'";
if ($conn->query($update) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
} ?>
<form action="" method="POST">
<button type = "submit" value = "like" name='like'style="font-size:24px"><?php echo $row['likes']; ?><i class="fa fa-thumbs-o-up"></i>
</form>
</div>
</div>
<?php endwhile; endif; ?>
Your while loop contains the update query so your code should be change like this.
in order to get the id to like you just need to use a hidden field to post that id like in this code
<?php
if($_POST['like']) {
$id=$POST['id'];
$update = "UPDATE posts set `likes` = `likes`+1 where `id` ='$id'";
if ($conn->query($update) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
} ?>
<?php
if ($sort == 1){
$result = $conn->query("SELECT * FROM posts ORDER BY date DESC LIMIT 4 ");
}
elseif($sort == 2)
{
$result = $conn->query("SELECT * FROM posts WHERE date > NOW() - INTERVAL 24 HOUR ORDER BY likes DESC");
}
elseif($sort == 3)
{
$result = $conn->query("SELECT * FROM posts ORDER BY likes DESC");
}
if ($result->num_rows > 0) :
while($row = mysqli_fetch_assoc($result)) : ?>
<div class="card mb-4">
<img class="card-img-top" src="<?php echo $row['image1'] ?>" alt="Card image cap">
<div class="card-body">
<h2 class="card-title"><?php print title; ?></h2>
<p class="card-text"><?php print text; ?></p>
Read More →
</div>
<div class="card-footer text-muted">
Posted on <?php print $row['date'] ?> by
<?php print $row['author']; ?>
<form action="" method="POST">
<input name="id" type="hidden" value="<?php echo $row['id']; ?>">
<button type = "submit" value = "like" name='like'style="font-size:24px"><?php echo $row['likes']; ?><i class="fa fa-thumbs-o-up"></i>
</form>
</div>
</div>
<?php endwhile; endif; ?>
<?php
require 'connect.inc.php';
$query = "SELECT `item`, `up`, `down` FROM mytable ORDER BY RAND() LIMIT 1";
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$item = $query_row['item'];
$up = $query_row['up'];
$down = $query_row['down'];
?>
<div id="one">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div id="two">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
<?php }
} else {
echo mysql_error();
}
?>
This is my code. I need to make it so when a user clicks the div id="one" or id="two" execute this sql query (if div one was clicked (same thing for two))
UPDATE mytable SET up=$up+1 WHERE id="1(can be any id)"
Also, can I do that math in an sql query?
Thanks
Alright so this consist of 3 parts:
1.html.
2.JS/ajax.
3.php.
1.) HTML.
<div data-action="up" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div data-action="down" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
2.) JS/Ajax.
<script type='text/javascript' >
$('.clicker').click(function (){
doAjaxCall($(this).attr('id'), $(this).attr('data-action'));
});
function doAjaxCall(varID, vote){
var pageUrl = document.URL;
ar post = '{"ajax":"yes", "varID":' + varID + ', "vote":' + vote + '}';// Incase you want to pass dynamic ID
$.post(pageUrl,post,function(data){
var response = $.parseJSON( data )
if(response.success){
//do whatever you like.
alert('baaaam');
}
});
}
</script>
3.) php.
if($_POST['ajax'] == 'yes'){
$field = $_POST['vote'];
$query = "UPDATE mytable SET `$field` = `$field` +1 WHERE id=".$_POST['var_id'];
$query_run = mysql_query($query);
$return = array();
$return['success'] = false;
if($query_run){
$return['success'] = true;
}
echo json_encode($return);
die()
}
Update whole Page
if($_POST['ajax'] == 'yes'){
$field = $_POST['vote'];
$query = "UPDATE mytable SET `$field` = `$field` +1 WHERE id=".$_POST['var_id'];
$query_run = mysql_query($query);
$return = array();
$return['success'] = false;
if($query_run){
$return['success'] = true;
}
echo json_encode($return);
die()
}
$query = "SELECT `item`, `up`, `down` FROM mytable ORDER BY RAND() LIMIT 1";
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$item = $query_row['item'];
$up = $query_row['up'];
$down = $query_row['down'];
?>
<div data-action="up" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div data-action="down" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
<script type='text/javascript' >
$('.clicker').click(function (){
doAjaxCall($(this).attr('id'), $(this).attr('data-action'));
});
function doAjaxCall(varID, vote){
var pageUrl = document.URL;
var post = '{"ajax":"yes", "varID":' + varID + ', "vote":' + vote + '}';// Incase you want to pass dynamic ID
$.post(pageUrl,post,function(data){
var response = $.parseJSON( data )
if(response.success){
//do whatever you like.
alert('baaaam');
}
});
}
</script>
<?php }
} else {
echo mysql_error();
}
?>
Basically this is the whole thing. if you want i can also put the pieces together for you.
You can add and onClick() event in javascript/jquery. Then, do a POST like this
$("#div1").onClick(function(){
var info = $(this).val();
$.post("fileWithQuery.php",{toUpdate: info},function(data){ // (fileName to post, variables to send via POST, callBack function)
// Show a message
});
});
You just need to create that php file.
I'm trying to make it so when I click a span icon it will send the article_id to my php sql page which deletes my article, I'm using jQuery Ajax to send the id, the id sends alright on the jQuery side but after the http post request is done my table row is still there, can anyone see if somethings wrong with my code, thanks in advance!
<?php
$sql_categories = "SELECT art_id, art_title, art_company, art_cat_id, art_sta_id, art_date, art_rating, art_price, cat_id, cat_name, sta_id, sta_name
FROM app_articles LEFT JOIN app_categories
ON app_articles.art_cat_id = app_categories.cat_id
LEFT JOIN app_status
ON app_articles.art_sta_id = app_status.sta_id
ORDER BY art_order ASC";
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row" id="page_<?php echo $row['art_id']; ?>">
<div class="column one">
<span class="icon-small move"></span>
<span class="icon-small edit"></span>
<span id="<?php echo $row['art_id']; ?>" class="icon-small trash"></span>
</div>
<div class="column two"><p><?php echo $row['art_title']; ?></p></div>
<div class="column two"><p><?php echo $row['art_company']; ?></p></div>
<div class="column two"><p><?php echo $row['cat_name']; ?></p></div>
<div class="column one"><p><?php echo $row['art_date']; ?></p></div>
<div class="column one"><p><?php echo $row['art_rating']; ?></p></div>
<div class="column one"><p><?php echo $row['art_price']; ?></p></div>
<div class="column one"><p><?php echo $row['sta_name']; ?></p></div>
<div class="column one"><span class="icon-small star"></span></div>
</div>
<?php
}
}
else {
echo "FAIL";
}
?>
jQuery
$(document).ready(function(){
$(".trash").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'ajax-delete.php',
data: 'delete_id='+del_id,
success:function(data) {
if(data) {
}
else {
}
}
});
});
});
PHP mySQL Statement
if(isset($_POST['delete_id'])) {
$sql_articles = "DELETE FROM app_articles WHERE art_id = ".$_POST['delete_id'];
if(query($sql_articles)) {
echo "YES";
}
else {
echo "NO";
}
}
else {
echo "FAIL";
}
?>
the reason your row is still there because AJAX call does not refresh the page. If you want your row to be removed you gotta do something like:
ASSUMING that your span click event is inside the row
$(".trash").click(function(){
var del_id = $(this).attr('id');
var rowElement = $(this).parent().parent(); //grab the row
$.ajax({
type:'POST',
url:'ajax-delete.php',
data: {delete_id : del_id},
success:function(data) {
if(data == "YES") {
rowElement.fadeOut(500).remove();
}
else {
}
}
});
Replace:
data: 'delete_id='+del_id,
with:
data: delete_id : del_id,