I Cannot get comment reply by Ajax under comment without refresh - javascript

I Cannot get comment reply by Ajax under comment, But reply saved in database and If i refresh Index.php page, it display correctly. So I think my problem either in my reply display element(Div id/class or php) OR Ajax call back.
Please help me. I can't do anything last 7 days about this.
my Index.php framework
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='$tutid' ORDER BY id DESC LIMIT 20") or die(mysqli_error($dbh));
echo'<div class="content"><comment>';
while($rows = mysqli_fetch_array($results)) {
$id = $rows['id'];
$username = $rows['username'];
//etc all
echo'<div class="post'.$id.'">
//Comments goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
echo'</div>';
// Reply Start
$query = "SELECT * FROM comments_reply WHERE parent_id ='".$id."'";
$res = mysqli_query($dbh,$query);
while($row = mysqli_fetch_array($res)){
$parent_id = $row['parent_id'];
$username = $row['username'];
//etc all
echo'<div class="rcontent"><replycomment><div class="reply'.$parent_id.'"><ul>
//Reply goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
</ul></div><replycomment></div>';
} //reply while close
} //comment while close
echo'<comment></div>';
my reply.php framework
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='$tutid' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$row = $results->fetch_array();
$id = $row['id'];
$res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE parent_id ='$id' LIMIT 1") or die(mysqli_error($dbh));
while($row = mysqli_fetch_array($res)) {
$parent_id = $row['parent_id'];
$username = $row['username'];
echo'<div class="rcontent"><replycomment><div class="reply'.$parent_id.'"><ul>';
//New reply goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
echo'</ul></div><replycomment></div>';
JavaScript { here $tutid is a page id, which work well ( If u have any confusion about this )}
$(document).ready(function(){
var inputReplycom = $(".replycom");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment"); // update comment
//update reply
function updateReplybox(){
var tutid = inputTutid.attr("value");
**(EDITED)** var RID = inputparent_id.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid="+ tutid,
complete: function(data){
**(EDITED)**
$(".postreply"+RID).append(data.responseText);
$(".postreply"+RID).fadeIn(2000);
}
});
}
//on submit reply
$(".replyfrm").click(function(){
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$(".loader").fadeIn(400);
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&replycom="+ replycom + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
$(".reply_here").hide();
updateReplybox();
}
});
//we prevent the refresh of the page after submitting the form
return false;
});
});
EDITED:
New Edited Code that I am trying now which display fadeIn a blank result before refresh
In index.php change:
<div class="postreply'.$parent_id.'"><ul>
In reply.php change:
<div class="postreply'.$parent_id.'"><ul>
JavaScript change
function updateReplybox(){
var tutid = inputTutid.attr("value");
var RID = inputparent_id.attr("value");
//just for the fade effect
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid="+ tutid,
complete: function(data){
$(".postreply"+RID).append(data.responseText);
$(".postreply"+RID).fadeIn(2000);
}
});
}

The following will be your js
$('#commentButton').click(function() {
replycom = document.getElementById('inputReplycom').value;
parent_id = document.getElementById('inputparent_id').value;
tutid = document.getElementById('inputTutid').value;
$.post('reply.php', {'replycom': replycom, 'parent_id': parent_id, 'tutid': tutid}, function(data) {
var parsed = JSON.parse(data);
var html = '<section class="comment-list block"><article id="comment-id-1" class="comment-item"> <a class="pull-left thumb-sm"> <img src="/uploads/' + parsed.photo +'" class="img-circle"> </a> <section class="comment-body m-b"> <header> <strong>'+parsed.username+'</strong> <span class="text-muted text-xs block m-t-xs">'+parsed.created_at.date+' </span> </header> <div class="m-t-sm">'+ parsed.comment +'</div></section> </article> </section>';
$('#extraComments').append(html);
}).success(function() {
$('#comment').val('');
$('#commentSuccess').html('Submitted successfully!').show().delay(5000).fadeOut();
}).fail(function() {
$('#commentFailed').html('Failed!').show().delay(5000).fadeOut();
});
});
in your reply.php get the data
$replycom = $_GET['replycom'];
$parent_id = $_GET['parent_id'];
$tutid = $_GET['tutid'];
//and process it
Please change the var names accordingly
Edited code :
echo json_encode(array('replycom' => $replycom, 'parent_id' => $parent_id, 'tutid' => $tutid));

Related

Load more to infifnite scrolling using jQuery and php

Recently i developed a load more functionality using php and jquery . Please see my code
Html
<div class="container clearfix product-output">
</div>
jQuery
$.ajax({
method: "POST",
url: "result.php",
data: { keyword:"all"}
}).done(function( msg ) {
$( ".product-output" ).html(msg);
$(".load-more").on("click",function(){
var load_num= $('.load-more').length;
var appear=[];
$(".im-product-block").each(function(){
appear.push($(this).attr('id'));
});
$.ajax({
method: "POST",
url: "result.php",
data: { keyword: "all", y_id: appear, load_num: load_num }
}).done(function(msg1){
$('.load-more-div').before(msg1);
if($(".hide-load").val()==1){
$(".load-more").hide();
}
});
});
});
In result .php i write the db connection code and following query .
$query = 'SELECT * FROM `product` ORDER BY id DESC LIMIT 15';
$query_1 = 'SELECT * FROM `product` ORDER BY id DESC';
if (ISSET($_POST['y_id'])) {
$appear = implode("', '", $_POST['y_id']);
$query = "SELECT * FROM `product` WHERE id NOT IN('{$appear}') ORDER BY id DESC LIMIT 15";
$query_1 = "SELECT * FROM `product` WHERE id NOT IN('{$appear}') ORDER BY id DESC";
}
$result = $conn->query($query);
$result_1 = $conn->query($query_1);
$total_num = $result_1->num_rows;
echo '<div class="container clearfix product-output">';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) { ?>
<div class="col-sm-2 im-product-block" id="<?php echo $row["id"]; ?>">
<p class="product-name"> <?php echo $row["name"]; ?></p></div>
<?php }
echo '</div>';
if ($total_num > 15 && $_POST[load_num] == 0) {
echo '<div class="load-more-div"><p class="load-more"> Load More</p></div>';
}
if ($total_num < 15) {
echo '<input type="hidden" name="hide-load" class="hide-load" value="1">
<div class="load-finished"><p class="load-f"> All Products Loaded Successfully</p></div>';
}
}
Here all this functionality is working fine . But instead of clicking load more button , when user scroll down to load-more it need to fetch the products automatically without clicking .
for that i using the following code
$(window).scroll(function() {
var hT = $(".load-more").offset().top,
hH = $(".load-more").outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
$(".load-more").trigger("click");
}
});
But here the execution is contunied to infinity .It is not stopping . Please check this code and suggest a good method
I think you need to stop your load executing while your ajax call is made and written to the page. Perhaps set a boolean variable to decide if you need to load more.
e.g.
var canLoad = true;
$(window).scroll(function() {
var hT = $(".load-more").offset().top,
hH = $(".load-more").outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH) && canLoad){
canLoad = false;
$(".load-more").trigger("click");
}
});
Set canLoad back to true once your ajax function has finished and you have loaded the data.

Why ajax won't populate my ul list?

All need is that ul list is populated with data from php code,on page load.Thanks in advance,and sorry if I am not exact,I am new here.This post is mostly code.
Here's the code of ajax function:
$(document).ready(function() {
var podtip="proba";
$.ajax({
url: 'php/dodajTVpocetna.php',
type: 'POST',
cache:false,
data: { target: podtip },
success: function (data) {
$('#slider ul').append(data);
}
});
});
Here's the code of php file:
$q = $_POST['target'];
$conn=mysqli_connect("localhost","root","","iptv");
if (mysqli_errno($conn)) {
die("Neuspjela konekcija: " . mysqli_connect_error());
}
else{
$upitM='SELECT * FROM stream WHERE Kategorija="Music" ORDER BY rand() LIMIT 0,1';
$music=mysqli_query($conn,$upitM);
$upitF='SELECT * FROM stream WHERE Kategorija="Movies" ORDER BY rand() LIMIT 0,1';
$film=mysqli_query($conn,$upitF);
$upitS='SELECT * FROM stream WHERE Kategorija="Series" ORDER BY rand() LIMIT 0,1';
$series=mysqli_query($conn,$upitS);
$upitN='SELECT * FROM stream WHERE Kategorija="News" ORDER BY rand() LIMIT 0,1';
$news=mysqli_query($conn,$upitN);
$upitMO='SELECT * FROM stream WHERE Kategorija="More" ORDER BY rand() LIMIT 0,1';
$more=mysqli_query($conn,$upitMO);
if(!$music)echo'greska je "'.mysqli_error($conn).'"';
while(($row = mysqli_fetch_assoc($music)) != NULL) {
$row1 = mysqli_fetch_assoc($news);
$row2 = mysqli_fetch_assoc($film);
$row3 = mysqli_fetch_assoc($series);
$row4 = mysqli_fetch_assoc($more);
print_r(error_get_last());
echo"<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row['Link']."\");'>".$row['Naziv']."</a></div></li>
<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row1['Link']."\");'>".$row1['Naziv']."</a></div></li>
<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row2['Link']."\");'>".$row2['Naziv']."</a></div></li>
<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row3['Link']."\");'>".$row3['Naziv']."</a></div></li>
<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row4['Link']."\");'>".$row4['Naziv']."</a></div></li>";
}
mysqli_close($conn);
}
HTML list:
<div class="w3-third">
<div id="liquid1" class="liquid">
<span class="previous"></span>
<div class="wrapper">
<ul id="slider">
</ul>
</div>
<span class="next"></span>
</div>
</div>
I used ajax before,and it worked this way.
first of all check your query , that return values and works fine use:
print_r($film) and other query result to see what happens at the end.
next you dont need to use
$('#slider ul').append(data);
use this:
$('#slider').append(data);
Change your PHP code with this :
$q = $_POST['target'];
$conn=mysqli_connect("localhost","root","","iptv");
if (mysqli_errno($conn)) {
die("Neuspjela konekcija: " . mysqli_connect_error());
}
else{
$upit='SELECT * FROM stream WHERE Kategorija in ("Music","Movies","Series","News","More") ORDER BY rand()';
$all=mysqli_query($conn,$upit);
if(!$all)echo'greska je "'.mysqli_error($conn).'"';
//uzimamo vrijednosti svih proizvoda za zadati podtip,smjestamo ih u div elemente i prikazujemo na pocetno
$ht = "";
while(($row = mysqli_fetch_assoc($all)) != NULL) {
print_r(error_get_last());
$ht .= "<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row['Link']."\");'>".$row['Naziv']."</a></div></li>";
}
mysqli_close($conn);
echo $ht;
}
And your js code :
$(document).ready(function() {
var podtip="proba";
$.ajax({
url: 'php/dodajTVpocetna.php',
type: 'POST',
cache:false,
data: { target: podtip },
success: function (data) {
$('#slider').append(data);
}
});
});
You have to accumulate the final HTML content on each iteration through resultset rows. Change your while loop as shown below:
$content = "";
while(($row = mysqli_fetch_assoc($music)) != NULL) {
$row1 = mysqli_fetch_assoc($news);
$row2 = mysqli_fetch_assoc($film);
$row3 = mysqli_fetch_assoc($series);
$row4 = mysqli_fetch_assoc($more);
//print_r(error_get_last());
$content .= "<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".addcslashes($row['Link'],'"')."\");'>".addcslashes($row['Naziv'],'"')."</a></div></li>";
}
echo $content;
Add dataType option into your ajax request object to get response from server as HTML:
...
dataType : 'html',
...
Also, append response data as HTML as shown below:
...
$('#slider ul').html(data);
...

Delete from data base with PHP, Ajax

Hi I am trying to run a delete script that will delete the record from my database using ajax and php. Used without the ajax javascript file the delete_file.php script works fine and is removed from the database.(So I am asssuming the problem lies in the javascript file somewhere.) Once I add the javascript file only it appears to run and delete_file.php does notk. Basically I pass three id's through to delete_file.php find them all in their respective tables then use those variables to find the right file to delete. Any Help is greatly appreciated. I need a fresh pair of eyes, thanks
What I am Clicking
[![enter image description here][1]][1]
html
<?php echo'<li class="col student_file">
<i class="fa fa-times-circle-o"></i>
<a class="the-file student_'.$student_id.'" id="file_'.$file_id.'" href="/application/student/file_management'.$file_path.'" target="_blank"><i class="fa fa-file-archive-o"></i></i></i>'.$file_name.' <span>'.$file_size.'</span></a>
</li>
delete_file_ajax.js
$(document).ready(function() {
"use strict";
$(".delete-file").click(function() {
var container = $(this).parent();
var id = $('.the-file').attr("id");
var string = 'id='+ id ;
if(confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "delete_file/delete_file.php",
data: string,
cache: false,
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
delete_file.php
<?php
session_start();
//Connect to Database
require_once('../../../../db_config.php');
$db_connect = connectDB($mysqli) or die(mysqli_error());
//First lets make sure the user is allowed
require_once('../../../../auth/admin_session.php');
//Create our session on session_id
$session_id = $_SESSION['ADMIN_ID'];
//Get the IDs
$s_id = $_GET['student'];
$a_id = $_GET['agent'];
$f_id = $_GET['file'];
//Lets find the Id of the Agency User
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = $a_id");
$session_row = mysqli_fetch_assoc($session_query);
$session_num_rows = mysqli_num_rows($session_query);
$agency_id = $session_row['agency_id'];
//Lets find the Id of the Agency User
$student_session_query = mysqli_query($db_connect, "SELECT * FROM students WHERE student_id = $s_id");
$student_session_row = mysqli_fetch_assoc($student_session_query);
$student_session_num_rows = mysqli_num_rows($student_session_query);
$student_id = $student_session_row['student_id'];
//Lets find the Id of the File we want to delete
$file_session_query = mysqli_query($db_connect, "SELECT * FROM uploaded_files WHERE file_id = $f_id AND agency_id = $a_id AND student_id = $s_id");
$file_session_row = mysqli_fetch_assoc($file_session_query);
$file_session_num_rows = mysqli_num_rows($file_session_query);
$file_id = $file_session_row['file_id'];
if(!mysqli_connect_errno()){
$stmt = $db_connect->prepare("DELETE FROM uploaded_files WHERE file_id = ? AND agency_id = ? AND student_id = ?") or die('We Could not locate the file you wish to delete');
$stmt->bind_param('iii', $file_id, $agency_id, $student_id);
$stmt->execute();
$stmt->close();
}
?>
Solution
html
echo '<form class="delete-student-file" action="delete_file/delete_file.php" method="post">';
echo '<li class="col student_file">';
echo '<input type="hidden" name="student-id" value="'.$student_id.'">';
echo '<input type="hidden" name="agency-id" value="'.$agency_id.'">';
echo '<input type="hidden" name="file-id" value="'.$file_id.'">';
echo'<a class="the-file student_'.$student_id.'" id="file_'.$file_id.'" href="/application/student/file_management'.$file_path.'" target="_blank"><i class="fa fa-file-pdf-o"></i>'.$file_name.' <span>'.$file_size.'</span></a>';
echo '<button class="delete-file" name="submit"><i class="fa fa-times-circle-o"></i></button>';
echo'</li>';
echo'</form>';
delete_file.php
//Get the IDs
$s_id = $_POST['student-id'];
$a_id = $_POST['agency-id'];
$f_id = $_POST['file-id'];
delete_file_ajax.js
$(document).ready(function() {
"use strict";
$(".delete-file").click(function(e) {
e.preventDefault();
var container = $(this).parent();
var formData = $('.delete-student-file').serialize();
if(confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "delete_file/delete_file.php",
data: formData,
cache: false,
beforeSend: function(){
container.animate({'backgroundColor': '#fb6c6c'}, 300);
},
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
});
}
});
});
It looks like your problem is sending the ajax call as POST and requesting it as GET. Try this:
$.ajax({
type: "GET",
url: "delete_file/delete_file.php",
data: string,
cache: false,
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
Personally, I would suggest changing your PHP to accept POST rather than GET, but that is just my opinion.
PHP know inside "" is string not variable,but enclose by '' can print variable
I advice you to use '' in sql query.
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = '$a_id'");
OR
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = '".$a_id."'");

Jquery getting more than one variable

I have a small script that runs a php file in the background and gets a variable every 3 seconds and put it in a div
script in document with div
<script>
$(document).ready(function() {
setInterval(function () {
$('#statmoney').load('safe.php');
}, 3000);
});
</script>
PHP FILE (safe.php)
$sql = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$money = htmlspecialchars($row->money);
echo $money;
If i need to add another variable i would need to make a new document is there a easy way to go about it?
UPDATE
menu.php
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['money', 'ore', 'energy']; // array of needed fields
$.ajax({
type: "POST",
url: "menusafe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
console.log(response)
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
<div class="menustats"><img src="graphics/logos/moneylogo.png" class="menustatimage"><div class="menustattext" id='money'></div></div>
<div class="menustats"><img src="graphics/logos/energylogo.png" class="menustatimage"><div class="menustattext" id="energy"></div></div>
<div class="menustats"><img src="graphics/logos/orelogo.png" class="menustatimage"><div class="menustattext" id='ore'></div></div>
PHP(menusafe.php)
<?php
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
?>
Let's imagine that we want to retrieve three fields from users table : firstname, age and money. In such case it would be better to use $.post or $.ajax method:
js part:
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['firstname', 'age', 'money']; // array of needed fields
$.ajax({
type: "POST",
url: "safe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
php part: (safe.php)
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}

For each ajax request,PHP return different results based on the time row was created

I have an ajax loop that returns recently created profiles from PHP encoded for JSON.
What i want to do is first return the most recently created profile and go to the second recently created profile and so on every time ajax sends a request to PHP.
How do i do this. So far the ajax loop just returns the same result since i can only get one recently created profile.
Here's my PHP:
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1")
or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['logo'] = $row['logo'];
$result['name'] = $row['name'];
echo json_encode($result);
}
?>
In the above php Block, if i remove 'limit 1' to something else, the ajax just stops working altogether.
Here's my ajax code:
get_fb();
var get_fb = (function(){
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
dataType : 'json',
type: "GET",
url: "../php/TopBusinesses_Algorythm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults =
$("<div style='margin-bottom:2px'><input name='1' type='submit' id='LogLogo' value=' '><span id='name' style='float:right; height:21px;font-weight:bold; color:#000; width:71%' class='goog-flat-menu-button'><span class='LogName'></span></span><span id='slogan'><span class='LogSlogan'></span></span><span id='services'><span class='LogServices'></span></span></div></div><span id='LogPid' style='height:170px; background-image:url(images/bg/iWhiteBg.fw.png)'></span></div>");
$('.LogName').html(feedback.name).attr('id' + counter);
$( '.LogSlogan' ).html(feedback.slogan);
$('.LogPId').html(feedback.pid);
$('.LogLogo').css('background-image', 'url(' + feedback.logo + ')' ).css('background-size', 'cover')
$buzfeedresults.append(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 7) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 2000);
})
});
};
})();
get_fb();
The problem is you output several JSON strings on the page try something like this:
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 10") or die (mysql_error());
$results = array();
while($row = mysql_fetch_array($Result)){
$result['logo'] = $row['logo'];
$result['name'] = $row['name'];
$results[]=$result;
}
echo json_encode($results);
you can do it in following ways:
declare counter variable globally(outside of get_fb() function) so that it will hold actual ajax call count
pass this counter value to ajax request
receive this counter value at your php end and use it as offset value to your sql(ex. limit offset,1)
======
edit
var counter = 0;
var get_fb = (function(){
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
dataType : 'json',
type: "GET",
url: "../php/TopBusinesses_Algorythm.php?counter="+counter
}).done(function(feedback) {
counter += 1;
var $buzfeedresults =
$("<div style='margin-bottom:2px'><input name='1' type='submit' id='LogLogo' value=' '><span id='name' style='float:right; height:21px;font-weight:bold; color:#000; width:71%' class='goog-flat-menu-button'><span class='LogName'></span></span><span id='slogan'><span class='LogSlogan'></span></span><span id='services'><span class='LogServices'></span></span></div></div><span id='LogPid' style='height:170px; background-image:url(images/bg/iWhiteBg.fw.png)'></span></div>");
$('.LogName').html(feedback.name).attr('id' + counter);
$( '.LogSlogan' ).html(feedback.slogan);
$('.LogPId').html(feedback.pid);
$('.LogLogo').css('background-image', 'url(' + feedback.logo + ')' ).css('background-size', 'cover')
$buzfeedresults.append(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 7) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 2000);
})
});
};
})();
get_fb();
<?php
require_once 'db_conx.php';
$counter = $_REQUEST['counter'];
if(!$counter)$counter=0;
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit $counter,1")
or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['logo'] = $row['logo'];
$result['name'] = $row['name'];
echo json_encode($result);
}
?>
=========
edit
var $buzfeedresults =
$("<div style='margin-bottom:2px'><input name='1' type='submit' id='LogLogo"+counter+"' value=' '><span id='name' style='float:right; height:21px;font-weight:bold; color:#000; width:71%' class='goog-flat-menu-button'><span class='LogName' id='log_name"+counter+"'></span></span><span id='slogan'><span class='LogSlogan' id='log_slogan"+counter+"'></span></span><span id='services'><span class='LogServices'></span></span></div></div><span id='LogPid"+counter+"' style='height:170px; background-image:url(images/bg/iWhiteBg.fw.png)'></span></div>");
$('#log_name'+counter).html(feedback.name);
$( '#log_slogan'+counter ).html(feedback.slogan);
$('#LogPId'+counter).html(feedback.pid);
$('#LogLogo'+counter).css('background-image', 'url(' + feedback.logo + ')' ).css('background-size', 'cover')
So i revised the structure of this Feed System and found out an easier way to do this is to generate the html from php.
So here's the PHP with HTML
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 10")
or die (mysql_error());
while($row = mysql_fetch_array($Result)){
echo '<div style="margin-bottom:2px">
<span id="name" style="float:right; height:21px;font-weight:bold; color:#000; width:71%">
<span class="LogName">'.$row['name'].'</span>
</span>
<span id="slogan" style="float:right; height:21px;color:#0D1; width:71%" class="goog-flat-menu-button">
<span class="LogSlogan">'.$row['slogan'].'</span>
</span>
<span id="services" style="float:right; height:21px;color:#000; width:71%" class="goog-flat-menu-button">
<span class="LogServices">'.$row['services'].'</span>
</span>
</div>
</div>
<span id="ProfileMap" style="height:170px; background-image:url(images/bg/iWhiteBg.fw.png)"></span>
<span id="LogPid" style="height:170px; background-image:url(images/bg/iWhiteBg.fw.png)"></span>
</div>';
}
?>
Ajax.
$.ajax({
type:"GET",
url:"../php/feed.php"
}).done(function(feedback){
$('#feed').html(feedback)
});
and just one Div of HTML in the body to house the incoming HTML.
<body>
<div id='feed'></body>
</body>
Done.

Categories