Ajax/Php get more than 1 result - php

I've built up a script that is to get users posts from a database, and I'm almost there. The ajax calls and I get the 10 posts in the response in Firebug, only it shows only 1 post in the page when I click load more. What do I need to add to the code below to show 9 more results?
AJAX
<script type="text/javascript">
$(document).ready(function(){
$('.load_more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#load"+ID).html('Loading...');
$.ajax({
type: "POST",
url: "include/load_more_home_posts.php",
cache: false,
dataType: "json",
data: { streamitem_id: ID},
cache: false,
success: function(stream){
$("#articles").prepend("<div id='divider-"+stream['streamitem_id']+"'><div class='userinfo'>X</div><a href='/profile.php?username="+stream['username']+"'>"+stream['first']+" "+ stream['middle']+" "+stream['last']+"<span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+stream['streamitem_timestamp']+"</a><hr>"+stream['streamitem_content']+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+stream['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+stream['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a title='Like "+stream['first']+" "+ stream['middle']+" "+stream['last']+"s status' id='likecontext_"+stream['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+stream['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+stream['streamitem_id']+"'>Like</a></div><div style='width:50px;' id='likesprint"+stream['streamitem_id']+"'><a title='See who likes "+stream['first']+" "+ stream['middle']+" "+stream['last']+"s status' href='include/likes.php?streamitem_id="+stream['streamitem_id']+"' /></a></div></div></form></div><div id='streamdislike'><a id='dislikecontext_"+stream['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+stream['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+stream['streamitem_id']+"'>Dislike</a></div><div style='width:70px;' id='dislikesprint"+stream['streamitem_id']+"'></div></div></form><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+stream['streamitem_id']+"'><div id='comment_list_"+stream['streamitem_id']+"'></div><div class='stream_comment_inputarea'><form id='mycommentform' method='POST' class='form_statusinput'>\
<input type='hidden' name='streamidcontent' id='streamidcontent' value='"+stream['streamitem_id']+"'>\
<input type='input' name='commentingcontents' id='commentingcontents' placeholder='Say something' autocomplete='off'>\
<input type='submit' id='button' value='Feed'><br/></div></div>");
// remove the previous load more link
$("#load"+ID).remove();
}
});
}
return false;
});
});
</script>
include/load_more_home_posts.php
<?php
session_start();
include("rawfeeds_load.php");
if (isset($_POST['streamitem_id']) && $_POST['streamitem_id'] != "") {
$lastID = mysqli_real_escape_string($mysqli,$_POST['streamitem_id']);
$json= array();
$following_string = mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_id = c.comment_streamitem
JOIN users AS u ON u.id = c.comment_poster
WHERE c.comment_poster = '$following_string'
AND d.streamitem_id < '$lastID'
AND (d.streamitem_target = '$following_string' OR
d.streamitem_creator = '$following_string')
ORDER BY d.streamitem_id DESC LIMIT 10";
$chant = mysqli_query($mysqli, $call) or die(mysqli_error($mysqli));
$json['streams'] = array();
while ($resultArr = mysqli_fetch_assoc($chant)) {
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
$json['streamdata'][] = $json;
}
echo json_encode($json);
}
?>

You recive from PHP an JSON like [{item1, item2},{item11, item12},...] and without iterate over it you are using only first group. I think the best and the easiest way will be using $.getJSON function instead of $.ajax. Look here at the second example, I think it is all you need to handle JSON received from PHP.

Related

Can't get post value

i have problem with the post value in my form
i show you my code and see if you can help me
<script src="//netsh.pp.ua/upwork-demo/1/js/typeahead.js"></script>
<script>
$(document).ready(function() {
$('#ville').on('change', function(){
var id_ville = this.value;
$.ajax({
type: "post",
url: "lycee.php",
data: 'id_ville=' + id_ville,
success: function(result){
$("#lycee").html(result);
}
});
$('input.lycee').typeahead({
name: 'lycee',
remote: 'lycee.php?query=%QUERY'
});
});
})
</script>
<script >
and this is my php part code
$id_ville = mysql_real_escape_string($_POST['id_ville']);
if($id_ville!='') {
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = $conn->query ("SELECT nom_lycee
FROM ville_lycee
INNER JOIN ville ON ville.id_ville = ville_lycee.id_ville
INNER JOIN lycee ON lycee.id_lycee = ville_lycee.id_lycee
WHERE ville.id_ville = '" . $id_ville . "'
AND lycee.nom_lycee LIKE '%{$query}%' ");
$options = "<label value=''></label>";
$array = array();
while ($row = $sql->fetch_assoc()) {
$array[] = array (
'label' => $row['nom_lycee'],
'value' => $row['nom_lycee'],
);
}
echo json_encode ($array);
}
}
the problem is that i need the id_ville value first and then the Query to filtre

Getting correct value of num_rows back AJAX/JSON

I have a notification system that out puts the right value of 1 and updates the div accordingly when a user posts one on my wall.
{
"num":1,
"notification_id":"640",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=515",
"notification_triggeredby":"85",
"notification_status":"1"
}
But if a user posts twice it does nothing and doesn't update at all.
{
"num":1,
"notification_id":"641",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=516",
"notification_triggeredby":"85",
"notification_status":"1"
}
{
"num":1,
"notification_id":"642",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=517",
"notification_triggeredby":"85",
"notification_status":"1"
}
CLIENT SIDE
$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'";
$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_stream=1){
$("#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>
<? } ?>
SERVER SIDE
$json = array();
$com=mysqli_query($mysqli,"SELECT * from notifications WHERE notification_targetuser='$idw' AND notification_triggeredby='$ide' AND notification_status='1' ORDER BY notification_id")or die($mysqli);
while($row = mysqli_fetch_assoc($com)){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
echo json_encode($json);
}}
$sql = "UPDATE notifications SET notification_status = '2' WHERE notification_targetuser='$idw'";
$go = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
You're echoing the JSON results inside a loop, so if the loop executes more than once, the final result is not valid JSON data. It's just multiple chunks of JSON.
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
Then you'll need to adjust your Javascript to expect an array instead of a flat object.

Keep Ajax alive

I'm trying to get my ajax to request information from the server and also keep it alive for at least 1 minuite before having a break and restarting and getting and passing a new streamitem_id if their were one inserted since the last call.
Currently it runs so fast and only once and I don't understand why.
AJAX
<script type="text/javascript" charset="utf-8">
function wait() {
var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
$.ajax({
type: "POST",
url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
async: true,
cache: false,,
dataType: "json",
data: {streamitem_id: streamitem_id},
success: function (response) {
setTimeout("wait()",1000);
$("#homestatusid").prepend("MY INSERTED RESPONSE");
},
});
}
$(document).ready(function(){
wait();
});
</script>
PHP
if (isset($_POST['streamitem_id'])) {
$lastID = (int)$_POST['streamitem_id'];
if(empty($lastID)) {
die('timeout');
}
else {
$following_string = $_SESSION['id'];
$result="SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_id = c.comment_streamitem
JOIN users AS u ON u.id = c.comment_poster
WHERE d.streamitem_id > '$lastID'
AND c.comment_poster = '$following_string'
AND (d.streamitem_creator = '$following_string')
OR d.streamitem_creator IN $friendlist
AND d.streamitem_type_id NOT IN ('3')
ORDER BY '$lastID' DESC LIMIT 1";
$result = mysqli_query($mysqli, $result) or die(mysqli_error($mysqli));
while ($resultArr = mysqli_fetch_array($result)) {
$json = array();
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
echo json_encode($json);
}}}
setTimeout does not work like you expect. An ajax-request can't be "kept alive" like you want. The request is sent, the PHP-script returns the content and the ajax-script get's the result. All this happens within ~1-2 seconds.
If this is used for some sort of stream (as it looks like), you would have to make the function repeat itself again and again over a small interval.
I've changed your code like this:
<script type="text/javascript" charset="utf-8">
function wait() {
var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
$.ajax({
type: "POST",
url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
async: true,
cache: false,
dataType: "json",
data: {streamitem_id: streamitem_id},
success: function (response) {
$("#homestatusid").prepend("MY INSERTED RESPONSE");
},
});
}
$(document).ready(function(){
setInterval(wait,10000);
});
</script>
The ajax-script will fire every 10 seconds. You can edit the speed yourself, but keep in mind that too many requests in a short timeperiod can make your server crash/go slow.
In your PHP script, you'll need to use the sleep function in order to keep your connection alive.
Something like:
function callScript(callback) {
$.post('myscript.php',{data:data},function(data) {
if (data == -1) {
return callScript(callback);
}
return callback(data);
}
}
myscript.php
$interval = 50;
$iters = floor(1000 / $interval);
while($conditional === false) {
if (--$iters < 1) { die(-1); }
sleep($interval);
}
echo $json;
While this isn't exactly what you need, it can easily be adapted to what you need. I've done this with other stuff, while costly, you can use a sql statements to wait for entries to be added etc.

Ajax comments calling json into function

I'm working on ajax comments and wondering how I can get the items from the comment_add.php page with the below bit of code so then I can insert it into obj.innerHTML.
function addcomment(streamid,content,containerid,posterid,postername,postid){
var obj = document.getElementById(containerid);
$.post("../comment_add.php", { streamid: streamid,content:content} );
obj.innerHTML = obj.innerHTML + "<div class='stream_comment'><table width='100%'><tbody><tr><td valign='top' width='30px'><img style='border:none;padding:0px;height:30px;width:30px;border-radius:0px;' src='imgs/cropped"+posterid+".jpg' onerror='this.src="img/no_profile_img.jpeg";'></td><td valign='top' align='left'><a href='profile.php?username="+posterid+"'>"+postername+" </a>"+content+"</td></tr></tbody></table></div>";
COMMENT_ADD.PHP
<?php
session_start();
require"include/load.php";
if(isset($_POST['streamid'])&isset($_POST['content'])){
user_core::add_comment($_POST['streamid'],$_POST['content']);
}
$json = array();
$check = "SELECT comment_id,comment_streamitem, comment_content FROM streamdata_comments";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
mysqli_free_result($check1);
$check = "SELECT * FROM users WHERE id=".$_SESSION['id']."";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysqli_free_result($check1);
echo json_encode($json);
?>
I did try using this code. Yet everytime I comment, it adds it into the 1st post in the stream only, as where the top function doesn't, it adds it into the status the user comments on.
<script>
$(document).ready(function(){
$("form#mycommentform").submit(function(event) {
event.preventDefault();
var streamid = $("#streamid").val();
var content = $(this).children('#content').val();
$.ajax({
type: "POST",
url: "comment_add.php",
cache: false,
dataType: "json",
data: { 'streamid': streamid, 'content': content},
success: function(html){
$("#commentaddid").html("<div class='stream_comment_holder' id='comment_holder_"+html['comment_streamitem']+"'><div id='comment_list_"+html['comment_streamitem']+"'><div class='stream_comment' id='comment_"+html['comment_id']+"'>div class='stream_comment_holder' id= style='display:;'><div class='stream_comment'><table width='100%'><tbody><tr><td valign='top' width='30px'><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+html['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></td><td valign='top' align='left'><a href='profile.php?username="+html['username']+"'>"+html['first']+" </a>"+html['comment_content']+"</td></tr></tbody></table></div></div></div></div>");
}
});
return false
});
});
</script>
It looks like the top function gets passed a containerId which it uses to know where to put the comment. However, the lower ajax version always puts the comment into #commentaddid.
It is not clear where in the DOM you want the comment to appear, but wherever it is you will need to replace the #commentaddid selector with it's selector.

Ajax update on div with a id

How would I go about updating a div with a id every x seconds? I want it to update the users statuses which are contained inside this, that includes the time the amount of comments made on that individual post.
I've tried setInterval but it takes 10 seconds for the status to be added and then duplicates the status every x amounts of seconds after that. All I need is for the response data to be updated not the insertion of the comment to be re-added every 10 seconds.
HTML:
<div id='divider-"+response['streamitem_id']+'></div>
JavaScript:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
cache: false,
dataType: "json",
data: { toid: content, newmsg: newmsg },
success: function(response){
$("#homestatusid").html("<div id='divider-"+response['streamitem_id']+"'><div class='userinfo'>X</div><a href='/profile.php?username="+response['username']+"'>"+response['first']+" "+ response['middle']+" "+response['last']+"<span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+response['streamitem_timestamp']+"</a><hr>"+newmsg+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+response['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+response['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a id='likecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+response['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'>Like</div></a><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'></div></div><div id='streamdislike'><a id='dislikecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+response['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'>Dislike</div></a><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'></div></div></div><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+response['streamitem_id']+"'><div id='comment_list_"+response['streamitem_id']+"'><table width=100%><tr><td valign=top width=30px><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><td valign=top align=left><div class='stream_comment_inputarea'><input id='addcomment' type='text' name='content' style='width:100%;' class='input_comment' placeholder='Write a comment...' onkeyup='growcommentinput(this);' autocomplete='off' onkeypress=\"if(event.keyCode==13){addcomment("+response['streamitem_id']+",this.value,'comment_list_"+response['streamitem_id']+"',"+response['id']+",'"+response['first']+" "+ response['middle']+" "+response['last']+"');this.value='';}\"><br/></div></div>");
}
});
return false
});
});
INSERT.PHP
$json = array();
$check = "SELECT streamitem_id FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_id DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_id'] = $resultArr['streamitem_id'];
mysql_free_result($check1);
$check = "SELECT streamitem_timestamp FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_timestamp DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
mysql_free_result($check1);
$check = "SELECT username, id, first, middle, last FROM users";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysql_free_result($check1);
echo json_encode($json);
First wrap up the Ajax call in a single-execution function, with the callback function referring to the same:
$(function() {
(function ajaxcall() {
$.ajax({
url: 'foo.php',
data: {boo:'moo',goo:'loo'},
timeout: function() { ajaxcall(); },
success: function(data) {
//do somethng with the data
//done, now call the function again:
ajaxcall();
}
});
}());
});
Then in the PHP write something like:
$timeout = 30;
$pollinterval = .5;
$counter = 30;
while ($counter >= 0) {
//function which fetches fresh data and sets $test to true if data is returned
list($test,$dataarray) = fetchdata();
if ($test) { //JSON_encode the data array and send it
echo JSON_ENCODE($dataarray);
}
else { //no fresh data, query the db again after wating for some time)
usleep($pollinterval*1000);
$counter -= $pollinterval;
}
//timeout, return whetever you have!
echo JSON_ENCODE($dataarray);
You can use setInterval (see Documentation) or setTimeout (see Documentation).
Sounds like polling. You can include an AJAX call, that will send a request to a backend PHP script that will search the database for further update. if found, it will immediately return the new result. The client side JS on receiving the new data, will wait for say 30 seconds before making another request. If the PHP doesn't find any new data, then it will query the DB again, say after 5 seconds, and continue to do so until a script-defined timeout, say 25 seconds, occur. Then it will return an empty result, on receiving which the client side JS will immediately make another request.
I think this is what you're wanting, using Jquery:
HTML:
<div id="divider-whatever"></div>
Jquery:
$(document).ready(function() {
setInterval(function() {
div = $("#divider-whatever");
$.get(data.php, function(responseData) {
div.html(responseData);
}, 1000);
// change 1000 to whatever time you need
// change data.php to the file where your data is coming from
});
});
*not tested
Hope this helps!

Categories