Notifications system getting all new records - php

So I've built all of the basic functionality, but with a major flaw. I search from the last id inserted which is fine.. But the error is when I get to the PHP. I search for MAX id and it sends back the last record obviously.. But if a user does three actions that sends a notification to you, then the other two don't show via the call, only when the page refreshes.
So what would I have to change to get all the notifications from the database when each call is made from the last id it searches for in the front end? I presume maybe a while loop in the PHP page rather than the max id. but then how would the back end select ALL new data from the front ends last max id?
So this is what I have.
<?
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select MAX(notification_id) AS notification_id ,notification_status,notification_targetuser,notification_triggeredby,notification_throughurl from notifications WHERE notification_targetuser='$user1_id' AND notification_status=1 ORDER BY notification_id DESC LIMIT 1";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id']?>";
var notification_targetuser="<?php echo $notification['notification_targetuser']?>";
var notification_triggeredby="<?php echo $notification['notification_triggeredby']?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&notification_targetuser="+notification_targetuser+"&notification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
if(data.notification_id>notification_id){
$("#notif_ui"+notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-" class="notif_actual_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br/></div></div></div><hr/>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
if(!data.notification_id.length) {
//no results...
return;
}
notification_id = data.notification_id;
}
}
});
}
setInterval(loadIt, 10000);
</script>
PHP
$json = array();
$com=mysqli_query($mysqli,"select MAX(notification_id) AS notification_id,notification_content,notification_time,notification_triggeredby,notification_throughurl from notifications where notification_id > '$id' AND notification_targetuser=".$_GET['notification_targetuser']." AND notification_triggeredby=".$_GET['notification_triggeredby']." AND notification_status=1");
$num = mysqli_num_rows($com);
if($num>0){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
$json['notification_content'] = $resultArr['notification_content'];
$json['notification_throughurl'] = $resultArr['notification_throughurl'];
$json['notification_triggeredby'] = $resultArr['notification_triggeredby'];
$json['notification_time'] = $resultArr['notification_time'];
mysqli_free_result($com);
echo json_encode($json);
}

I in fact used mysqli_free_result($com);within the while loop preventing more than one set of results returning and therefore removed this from the query.

Related

Fetch random row from MySQL on click

I am creating a random quote generator and store the data in a MySQL database.
The code is working but it continues to fetch the same row and not a new random row everytime I click. But if I wait for say 30 seconds and click again, it works as it should. I just want it to work right away on click.
<script type="text/javascript">
$(document).ready(function() {
$(".display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(response, 5);
//alert(response);
}
});
});
});
I suspect the timeout function is not working properly as it takes longer to fetch a new row. I used the order by Rand() to get the random row. My PHP looks like this:
<?php
include("connect.php");
$finds = "SELECT * FROM citater5 ORDER BY RAND() LIMIT 1";
$result = mysql_query($finds, $con) or trigger_error(mysql_error()." ".$finds);
while($data = mysql_fetch_row($result))
{
echo "<aside class=\"citatout\">";
echo "<div id=\"paradiso\" class=\"text-vertical-center-q\">";
echo utf8_encode("<h1 class=\"animated fadeIn\" align=center>$data[0]</h1>");
echo utf8_encode("<h2 class=\"animated fadeIn\" align=center>$data[1]</h2>");
echo "</div>";
echo "</aside>";
}
?>
Why is a new row not being fetched every time?
Not quite sure if ORDER BY RAND() is working as you want it too.
- I haven't really been working with PHP for a few years, but I would probably try something like this out:
<?php
include("connect.php");
$totalrows = mysql_num_rows(mysql_query("SELECT * FROM citater5"));
$finds = "SELECT * FROM citater5 WHERE id='".rand(1,$totalrows)."'";
$result = mysql_query($finds, $con) or trigger_error(mysql_error()." ".$finds);
$data = mysql_fetch_row($result);
echo "<aside class=\"citatout\">";
echo "<div id=\"paradiso\" class=\"text-vertical-center-q\">";
echo utf8_encode("<h1 class=\"animated fadeIn\" align=center>$data[0]</h1>");
echo utf8_encode("<h2 class=\"animated fadeIn\" align=center>$data[1]</h2>");
echo "</div>";
echo "</aside>";
?>
And - as you're only getting 1 result, theres no need to run it through a while().
Hope this helps a bit.
Like the others said, rand() may not be the best to use, but I don't think it is what is causing your issue. Most likely the result is being cached if it's displaying the same result for a short period of time.
You could try turning the cache off:
$.ajaxSetup({ cache: false });
Or append the URL in the ajax call with a random number or timestamp.

PHP loading items from the database into a div on load more button click

I have a main.php page where I have a while loop that displays the first 10 items from the database. I want to load the next 10 items once a load more button is clicked.
$res = mysql_query("SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 10");
if($res && mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$id = $row['id'];
?>
<div class="main_page">
item id <?php echo $id; ?>
</div>
<button class="load_more">Load More</button>
....
What is a good way of doing this? Any help is much appreciated!
UPDATE:
right now i have this script for the load more button:
<script type="text/javascript">
$(document).ready(function(){
$(".load_more").click(function (){
$('.load_more').html('<img src="images/ajax-loader.gif" />');
$.ajax({
url: "loadmore.php?id=" + $(".ad_display:last").attr("id"),
success: function(html){
if(html){
$(".main_page").append(html);
$('.load_more').html('Load More');
}else{
$('.load_more').replaceWith('No posts');
}
}
});
});
});
</script>
after the form of the filters is submitted, the url looks somewhat like this:
index.php?search=&category=0&ad_order=1
how do I pass on the search (even if empty), ad_order, and category value to the loadmore.php?
limit 0, 10 will display the first 10 items from your query. limit 20,10 will display 10 items starting with the 20th item (counting from zero). You can pass the page number or the number of items retrieved up to now in a parameter when you call the page that does the query. This will involve either reloading the current page with a different start index in limit, or issuing an ajax query that lets you load more items without reloading the page.
Apart from the answer posted by Octern, not sure what you want to achieve for your second question but try:
<script type="text/javascript">
//saving the GET variables
ad = <?php echo $_GET['ad_order']; ?>
catg = <?php echo $_GET['category']; ?>
search = <?php echo $_GET['search']; ?>
//default value of record to start from
rec = 0;
$(document).ready(function(){
$(".load_more").click(function (){
$('.load_more').html('<img src="images/ajax-loader.gif" />');
$.ajax({
//passing them here
//URL updated to pass rec
url: "loadmore.php?id=" + $(".ad_display:last").attr("id")+"&search="+search+"&category="+catg+"&ad_order="+ad+"&rec="+rec,
success: function(html){
//updating counter to start from record
rec += 10;
if(html){
$(".main_page").append(html);
$('.load_more').html('Load More');
}else{
$('.load_more').replaceWith('No posts');
}
}
});
});
});
</script>
In your loadmore.php you need to relevant code to fetch the above $_GET values
Your query will be something like:
$res = mysql_query("SELECT * FROM classifieds WHERE date < '".mysql_real_escape_string($_GET['id'])."' AND search = '".$_GET['search']."' AND category = '".$_GET['category']."' AND ad_order = '".$_GET['ad_order']."' ORDER BY date DESC LIMIT '".$_GET['rec']."',10");
So everytime you click on the load_more, the limit will change as LIMIT 0,10 -> LIMIT 10,10 -> LIMIT 20,10 etc.

Saving sortable to mysql with ajax jquery and php

I have a page with multiple drag&drop boxes, that works great, the thing that does not work are the links in the boxes. I would appreciate if someone could help me :). So I have a page where people can drag&drop boxes (it works fine, as I said before), the links inside the boxes are sortable aswell, but I can't seem to get them to save the values to mysql. I think there is a conflict between the two drag&drops, maybe I am doing it wrong, 'cause I haven't used ajax and jquery before.
//here is the jquery where I need to add some ajax
$(function() {
$('.dragbox-content').sortable({
connectWith: '.dragbox-content',
update: function(event, ui) {
var order=$(this).attr('id');
alert(order); // I get the order alert and it has one value that I need, but I need the sort order aswell
}
});
});
//this is the <div> that has the links in them and mysql query that gets the values
//from two different databases, one is for the boxes and the other for links.
//boxes db id = links title_id
echo '<div class="dragbox-content" id="order'.$widget['id'].'"';'>''</div>';
$sql10 = "SELECT u.*, w.id, w.link_address, w.link_name FROM db_boxes u LEFT
JOIN db_links w ON u.link_id = w.id WHERE
(u.username = '$username' AND u.link_id !='0' AND w.title_id = '".$widget['id']."'
AND w.link_name !='pilt' AND w.rights = '0') OR
(u.username = '$username' AND u.link_id !='0' AND w.title_id = '".$widget['id']."'
AND w.link_name !='pilt' AND w.rights LIKE '%26%') ORDER BY w.id ASC";
$result10 = mysql_query($sql10) or die (mysql_error());
while ($row = mysql_fetch_array($result10)) {
$link_id = $row['id'];
$link_address = $row['link_address'];
$link_name = $row['link_name'];
$title_id = $row['title_id'];
?>
<div class="move" id="<?php echo $link_id;?>">
<span class="link_style">
<div><?php echo $link_name;?> </div</span></div>
I just need somebody to tell me how can I save tile_id and sort_order to boxes database with ajax on every click a user makes on that page
See my example below:
http://jsfiddle.net/gRoberts/vMy7r/
$(function () {
$('ul').sortable({
update : function(e, ui) {
var ul = $(ui.item).closest('ul');
var index = 0;
var toPost = {};
ul.find('> li').each(function() {
index++;
$(this).find('input').val(index);
toPost[$(this).find('input').attr('name')] = index;
});
$.ajax({
url : '/echo/json/',
data : toPost,
type : 'POST',
dataType : 'json',
success : function(resp) {
alert(resp);
},
error : function() {
alert('There was a problem');
}
});
}
});
});
​
The above example can be used in two ways, if you remove the $.ajax it will update hidden form fields which you can then post normally.

Re-aligning return value from php function in the html

I have am trying to create a simple voting page. There are a few links on each side and when the user click the up arrow the vote is counted and the vote count value is increased. Everything works right now except that when the vote is increased the new value appears on top of the upvote arrow (which makes sense since I am echoing the new value). I have not been able to figure out how to set the updated vote count into the SPAN which should show the vote count.
Here is the code:
HTML
<?php
$sql=mysql_query("SELECT * FROM discussion_links WHERE link_side = 'Michigan'");
while($row = mysql_fetch_array($sql)) {
$link_id=$row['link_id'];
$url=$row['link_url'];
$title=$row['link_title'];
$source=$row['link_source'];
$votes=$row['vote_count'];
?>
<div class="top-links-wrapper">
<div class="link-info">
<a class="link-title" href="http://<?php echo $url ?>"><?php echo $title . "</a>"; ?>
<p class="link-source"><?php echo $source . "</p>" ?>
</div>
<div class="link-vote-wrapper">
<div class="link-votes">
<span><?php echo $votes; ?></span>
</div>
</div>
</div>
<?php
}
?>
I would like to replace the value returned from the PHP function below into the SPAN in the code above.
PHP
<?php
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id']) {
$id=$_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql=mysql_query("select ip_add from Voting_IP where link_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
if($count==0) {
// Update Vote.
$sql = "update discussion_links set vote_count=vote_count+1 where link_id='$id'";
mysql_query( $sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into Voting_IP (link_id_fk,ip_add) values ('$id','$ip')";
mysql_query( $sql_in);
}
else {
echo "<script>alert('You have already voted');</script>";
}
$result=mysql_query("select vote_count from discussion_links where link_id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['vote_count'];
echo $up_value;
}
?>
This $up_value is the one I would like to replace the current vote count in the HTML.
jQuery
<script type="text/javascript">
//<![CDATA[
var $j = jQuery.noConflict();
$j(function() {
$j(".vote").click(function() {
var id = $j(this).attr("id");
var name = $j(this).attr("name");
var dataString = 'id='+ id ;
var parent = $j(this);
if (name=='up') {
$j(this).fadeIn(200).html('<img src="dot.gif" />');
$j.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});
//]]>
</script>
Thanks and any help would be greatly appreciated.
Assuming that you are returning the appropriate (int) total back in the success function,
then you should just set the InnerHTML of the span element to that value
It would be convenient if you were to give each link-votes element a unique ID and use that id to change the InnerHTML of the span element. on ajax success
Since you are already associating the vote_id with the event handler, then you
could simply add a prefix to the span id element, and then in the success function,
call something like this:
$("#myPrefix"+id).html(html);

Retrieve Data from database if new records added in database

Hello i have gone through Long polling, websockets and APE, Ajax push, Ajax Pull. As the technology of websockets isnt yet much introduced in our World Wide Web now. i thought i would use the normal setInterval functions to check the database. this is for a chat application, my code :-
on Home.php :
Javascript:
$(document).ready(function(){
setInterval(function(){
var id = $id; // this is the id of the last message inserted in the database
var data = 'id='+id;
$.ajax({
type : "POST",
url : "check.php",
data : data,
success : function(data){
if(data)
{
$(".comments").append(data);
}
}
});
},1000);
and check.php
php code :
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM messages WHERE id>'$id' ORDER BY id DESC");
$num2 = mysql_num_rows($get);
$get2 = mysql_fetch_assoc($get);
$id = $get2['id'];
if($num2!=0)
{
$username = $get2['username'];
$a = mysql_query("SELECT * FROM people WHERE username='$username'");
$n = mysql_num_rows($a);
$b = mysql_fetch_assoc($a);
$file = $b['filename'];
$pic = "<img src=\"images/" .$file. "\" width=\"40\" height=\"40\">";
$name = $get2['fullname'];
$message = $get2['message'];
echo $pic.$message."<br/>";
}
else
{
}
if there is a new record inserted in the database it echo's out properly but then it doesnt update the $id in the home.php page so it sends the old id again and again and the comment gets appended again and again.
what i want is. for every interval . the $id of the home.php should be updated so that it sends only the present message id to the check.php page.
I gues that the first code you've post is in your template of home.php and the $id then goes replaced with the real number of the last ID.
this works for the first time when the page is processed with PHP, but once downloaded on users machine, you only have to rely on JavaScript...
I'm not sure in which form you receive the data from check.php, but you need to do something like
id = data.id
data = 'id='+id;

Categories