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.
Related
I have successfully created a <textarea> that posts content to the database without a need for button or page refresh. However, for design purposes I would like to use an editable <div>. So I've used contenteditable="true". However, the ajax post no longer works with <div>.
My Code:
$(document).ready(function() {
var timer;
$('#about').on('input', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
var about = $('#about').val().trim();
$.ajax({
url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
type: 'post',
data: {
about: about
},
success: function(response) {
$('#cid').val(response);
}
});
}, 2000);
});
});
/* This is comment.php */
<?php
session_start();
require_once 'config/config.php';
require_once 'includes/auth_validate.php';
$cid = $_GET['customer_id'];
$about = $_POST['about'];
$sql = ("UPDATE patient_id SET about = ? WHERE id = ?;");
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "si", $about, $cid);
mysqli_stmt_execute($stmt);
?>
Textarea
<div id="about" type="text" name="about" class="content livecomments" contenteditable="true" onpaste="OnPaste_StripFormatting(this, event);"><?php echo $edit ? ( empty( htmlentities ($row[ 'about' ]) ) ) ? 'test' : htmlentities ($row[ 'about' ]) : '';?></div>
The problem is here
var about = $('#about').val().trim();
<div> elements doesnot have value. You should use html() or text()
var about = $('#about').text().trim();
I am loading data from a mysql table into a html table. I am using AJAX php Jquery to accomplish this. I need to make sure that the way I built this will work regardless of how much data is in the table.
Right now I am working with a table that is 5000 rows long but there will eventually be 88000 rows in this table.
I know if I load all the data on page load this could end up bogging down the server and the load time of the page.
My question is the way my logic is now will it load all the results into the $results and only query the needed amount of rows because it is paginated. Or even though it is paginated is my webpage taking every row in the whole database for load time.
if the whole table is being loaded how can I change the query to only load the data when needed. It loads on page scroll.
Also I need to write a search function. Since the data is paginated would I search the data in $results or query the table with separate search functions? Which way would provide less load times which would cause a bad experience for my user?
The AjAX
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = true;
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == true) {
displayRecords(limit, offset);
busy = false;
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
This is how I am querying the database
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 5;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
By transferring a JSON object from the server the limit, offset and html (and maybe others lime status_messsage, etc.) values could be transferred to the client at the same time.
On the client side I meant something like this:
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#productResults").append(json.html); // corr to $output['html']
$('#loader_image').hide();
if (json.html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
...and on the server side:
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
// Make sure to handle invalid offset values properly,
// as they are not validated from the last request.
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
$output['html'] .= $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
$output['html'] .= '<tr class="invent">';
$output['html'] .= '<td>' . $res['wuno_product'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_alternates'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_description'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_onhand'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_condition'] . '</td>';
$output['html'] .= '</tr>';
}
}
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
I do this exact thing you want on my site http://www.flixnetforme.com/ where as you can see as you scroll to the bottom of the page the next set of records is loaded. I have over 150,000 records but it only loads 36 at a time when the user scrolls to the bottom of the page.
The way you want to do this is is by loading your first initial records through ajax and not hardcode them into the page.
index.php
$(document).ready(function(){
var last_id;
if (last_id === undefined) {
genres = $("#genres").val();
$.ajax({
type: "POST",
url: "includes/getmorefirst.php?",
data: "genres="+ genres,
success: function(data) {
$( ".append" ).append(data);
}
});
};
};
<html><div class="append"></div></html>
In this example when the user gets to the page and is loaded it calls getmorefirst.php and return the first records.
getmorefirst.php is a file that will load the first set amount of records you want to show when the user gets to the page. In my case I load 36 records at a time when a user scrolls to the bottom of my page.
getmorefirst.php
$sql = "SELECT * FROM table ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
The last_id div is important so that ajax will know the last record sent and which one to pick up after when it loads the next set of 36 records.
.append is the div where I am appending the data from ajax when the user its the bottom.
.last_id is your key to knowing how to load the next set of records. In whatever order you send the records back its important that ajax knows the last ID of the record loaded so it knows where to start loading the next time ajax calls for more records. In my case when the users scrolls to the bottom of the page.
when user scrolls to bottom of index.php
if($(window).scrollTop() === $(document).height() - $(window).height()) {
last_id = $(".last_id:last").attr("id");
$.ajax({
type: "POST",
url: "includes/getmore.php?",
data: "last_id="+ last_id,
success: function(data) {
$( ".append" ).append(data);
}
});
return false;
};
};
last_id = $(".last_id:last").attr("id"); will get the last ID sent.
data: "last_id="+ last_id, will send the last id to getmore.php so it knows the last id of the record sent.
getmore.php
$sql = "SELECT * FROM table WHERE ID > '$last_id' ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
As you can see getmore.php will return the next 36 records but AFTER the last_id sent.
Hope this make sense and gives you a start.
Here is a reduced example of the JSON / AJAX mechanism that I have tested:
HTML (file test.html)
<html>
<head>
<!-- THE NEXT LINE MUST BE MODIFIED -->
<script src="../jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var limit = 5;
var offset = 0;
// THE NEXT LINE MUST BE MODIFIED
var assetPath = "http://www.example.com/stackoverflow/test.php"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
async: true,
cache: false,
beforeSend: function() {
$("#content").html("");
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#content").html(json.html);
window.busy = false;
}
});
}
</script>
</head>
<body>
<div id="content"></div>
<div onclick="displayRecords(limit,offset); return false;" style="cursor:pointer">Click to Call</div>
</body>
</html>
PHP (file test.php)
<?php
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
$output['html'] .= '<span style="color:red;">limit='.$output['lim'].', offset='.$output['offs'].'</span>';
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
Result
1st time
2nd time
nth time
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);
}
I have a Ajax PHP Show More feature like youtube and Live search scripts but I can't get them to work together. For example my live search works but then the show more feature doesn't work with it on the search results and when I use the show more then the live search doesn't work.
They don't seem to be messing with each other. Can anyone help me out? I am new to this website so I will try my best to show my code and explain it.
INDEX.PHP
<?php
include_once("connect.php");
$sql = "SELECT COUNT(*) FROM database";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
$item_per_page = 3;
$total_rows = mysqli_fetch_array($query);
$pages = ceil($total_rows[0]/$item_per_page);
?>
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Show More Scripted
$(document).ready(function() {
var track_click = 0;
var total_pages = <?php echo $pages; ?>;
$('#news-table-wrap').load("showmore_search.php", {'page':track_click}, function() {track_click++;});
$(".load_more").click(function (e){
$(this).hide();
$('.animation_image').show();
if(track_click <= total_pages){
$.post(showmore_search.php',{'page': track_click}, function(data) {
$(".load_more").show();
$("#news-table-wrap").append(data);
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
$('.animation_image').hide();
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError){
alert(thrownError);
$(".load_more").show();
$('.animation_image').hide();
});
if(track_click >= total_pages-1){
$(".load_more").attr("disabled", "disabled");
}
}
});
});
// Live Search Script
function searchNews(value) {
$.post("showmore_search.php", {newsResult:value}, function(data){
$("#news-table-wrap").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="search" id="search" class="search-box" onKeyUp="searchNews(this.value)" placeholder="Search News">
<table id="news-table-wrap" class="news-table-wrap" cellpadding="0" cellspacing="0">
</table>
<div align="center">
<div class="load_more" id="load_more_button">Show More</div>
<div class="animation_image" style="display:none;"><img src="/files/ajax-loader.gif"></div>
</div>
</body>
</html>
SHOWMORE_SEARCH.php
<?php
include_once("connect.php");
$newsResult = $_POST['newsResult'];
$item_per_page = 3;
$page_number = $_POST["page"];
$position = ($page_number * $item_per_page);
$sql = "SELECT * FROM database WHERE headline LIKE '%$newsResult%' OR post LIKE '%$newsResult%' ORDER BY date DESC LIMIT $position, $item_per_page";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
$headline = $row['headline'];
$author = $row['author'];
$date = $row['date'];
$post = $row['post'];
$name = $row['name'];
echo "<tr class='news-preview-wrap'>";
echo "<td><div class='news-preview-content'><div class='news-preview-headline'><a href='news_post?name=".$name."'>".$headline."</a></div>
<div class='news-preview-date'>Written by ".$author." on ".$date."</div>
<div class='news-preview-post'>".$post."</div></div>
<div class='news-more'><a href='news_post?name=".$name."'>Read More</a></div></td>";
echo "</tr>";
} else {
echo "<div class='search-error'>No search results were found...</div>";
}
?>
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
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.