Load more return duplicate - javascript

I trying to make load more content from database via php and ajax and read some tutorial but what I tried return duplicate entry. (here is just an example of my real code:)
Query:
$sql = "SELECT name FROM table WHERE cat = 2 LIMIT 10";
This load first 10 items.
Query for load more:
$limit = $_GET['limit'];
$current = $_GET['current'];
$sql = "SELECT name FROM table WHERE cat = 2 LIMIT $current OFFSET $limit";
Ajax:
$('.getMore').click(function() {
var adslen = $('.Ads').length; // this return current items
var limit = $(this).attr('data-limit'); // this return current item and items after load more
$.ajax({
type: "GET",
data: {
limit: limit,
current: adslen
},
dataType: 'html',
url: '/api/fetch.php?getBrowse',
success: function(data) {
// do something
}
});
});
For example now we have 10 items, after click on loadMore it load another 10 items, but the problem is it load duplicate itemes too, what I have done wrong?
HTML:
<a class="getMore" id="browse-getMore" data-limit="10">More</a>
After press load more it update data-limit:
<a class="getMore" id="browse-getMore" data-limit="20">More</a>

The problem is that you do not specify order. In your case SELECT statement returns rows with no specific order. When you run it once, it may return one list of records, when you run it twice (the same select query) it may return another set of records. So, do it like so:
$sql = "SELECT name FROM table WHERE cat = 2 ORDER BY id LIMIT $current OFFSET $limit";
And read theory. It says that relation (or table) is an unordered set of records, unless you specify order explicitly. And by the way, if you specify order, it is no longer a relation, if I'm not mistaken.

Related

Show multiple rows from database(SQL) using php/javascript(ajax) to front end of website

I'm still very new to php and javascript(ajax) and I've tried looking at various posts and websites trying to find my answer, but to no avail.
I'm trying to show all related rows from my database on the front end of a website. My SQL statement is currently picking up all the rows I need, but I can't get it to show all the rows (I can get only one row to show).
Can someone guide me a bit and tell me what to do to get it right? My code is as follows:
PHP-
$result = mysql_query("SELECT lot_num, buyer_id, item_desc, quantity, price FROM auction_items where auction_id = (SELECT id FROM auction ORDER BY date_created desc Limit 1) ORDER BY id DESC"); //query
$table_data = array();
while($row = mysql_fetch_array($result)){
$table_data[]= (array('lot_num' => $row["lot_num"], 'buyer_id' => $row["buyer_id"], 'item_desc' => $row["item_desc"], 'quantity' => $row["quantity"], 'price' => $row["price"]));
}
// $array = mysql_fetch_row($result);
echo json_encode($table_data);
I'm also going to include my javascript(ajax) code to cover my bases:
$("#submit").click(function(){
$.ajax({
url: 'auctionItemLoad.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var lot_num = data[0];
var buyer_id = data[1];
var item_desc = data[2];
var quantity = data[3];
var price = data[4];
$('#lot_num_result').html(lot_num);
$('#buyer_id_result').html(buyer_id);
$('#item_desc_result').html(item_desc);
$('#quantity_result').html(quantity);
$('#price_result').html(price);
}
});
});
The reason only one row is showing is because you are only accessing data's first row, you have to iterate on all of its rows to show all of its data. Just like you iterate on all the sql request's result rows in your php file to add them to the $table_data array, you have to iterate on data in your ajax request's success callback, this time outputting the data. You can do this with JQuery's each function.
...
success: function(data) {
$.each(data, function(i, row) {
var lot_num = row.lot_num;
var buyer_id = row.buyer_id;
var item_desc = row.item_desc;
var quantity = row.quantity;
var price = row.price;
$('#lot_num_result').append(lot_num);
$('#buyer_id_result').append(buyer_id);
$('#item_desc_result').append(item_desc);
$('#quantity_result').append(quantity);
$('#price_result').append(price);
)};
}
...

Fetch number of rows using javascript

I'm trying to fetch number of rows that were not in another table and show them using javascript.
First, in the main page, it will list the inbox name from inboxtb table. Then I have a script that should pass the value (inboxid) to another file and return the number of result back to the main file, in its corresponding row.
I'll fetch first all the inbox row (main page):
while($stmt->fetch()){
echo '<li>'.$name.' <span id="loadnumber"></span></li>';
}
Then my script:
$(function(){
$('.loadmessage').ready(function(){
var elem = $(this);
var dataString = "inboxid="+elem.attr('data-artid');
var $parent = $(this).closest('loadmessage');
setInterval(function() {
$.ajax({
type: "GET",
url: "noofres.php",
data: dataString,
success: function(data) {
var $span = $parent.find('.loadnumber'); /* FIND THE CORRESPONDING SPAN */
$span.append(data); /* LOAD THE DATA INSIDE THE SPAN */
}
});
});
return false;
});
});
And my noofres.php:
if($stmt = $con->prepare("SELECT a.messageid FROM messagetb a LEFT JOIN readtb b ON a.messageid = b.messageid WHERE a.inboxid = ? AND b.readid IS NULL")){
$stmt->bind_param("i",$_GET["inboxid"]);
$stmt->execute();
$stmt->store_result();
$noofunreadmessages = $stmt->num_rows;
$stmt->close();
} /* END OF SECOND PREPARED STATEMENT */
echo '<span class="badges">'.$noofunreadmessages.'</span>';
But it doesn't return the numbers, where it should. What am I doing wrong? Or a better script to do it?
Very rough example output:
Person1 Message - 3
Person2 Message - 1
Person3 Message - 10
But my current output is:
Person1 Message
Person2 Message
Person3 Message
Number does not return the corresponding number at all. And error are showing up and continuously growing with this message.
Your code is incorrect in terms of logic.
You are executing AJAX once and receiving the value once as well.
Then, you update your element's HTML many times with the same one value.
$.ajax({}, {
success: function(data) {
setInterval(function() {
$('#loadunreadmessages').html(data);
}, 1000);
}
});
In order to get fresh values every time, you need to change it such way that it will execute AJAX many times and every time it will update value once. It sounds logical.
setInterval(function() {
$.ajax({}, {
success: function(data) {
$('#loadunreadmessages').html(data);
}
});
}, 1000);
In your case it is:
setInterval(function() { /* EVERY SECOND, IT EXECUTES NEW REQUEST TO GET FRESH VALUES */
$.ajax({
type: "GET",
url: "../fetch/noofres.php", /* THIS IS WHERE THE NUMBER OF UNREAD MESSAGES SHOULD COME FROM */
data: dataString,
success: function(data) {
$('#loadunreadmessages').html(data); /* LOAD THE NUMBER TO THIS SPAN WITH THE ID OF loadunreadmessages */
}
}) ;
}, 1000);

jtable single column/field in a table refresh

I am using Jtable for booking events. In combination with PHP, MySQL. My question is, is there a way to just reload every 10 second single column. Precisely I have something like this:
Checkbox ID Event Reservations
+ 4 ev1 22
- 5 ev2 19
I would like to have the reservations column reloaded every 10 seconds, so the user that is logged in can see the changes. Now I got it working with reloading the whole table, but this is not what I really need because every user can book only 9 events and I need to have checkboxes at the left side. After reloading the whole table my checkboxes are not working as expected. So is there a way to reload just one column? My code right now is:
window.setInterval(function(){
$('#Events').jtable('reload');
}, 10000);
Any help or suggestion would be appreciated.
I found a way around how to solve it:
First create a new field in JS like this:
test: {
title: 'test',
display: function (data) {
var $div = $('<div id="test"">'+data.record.id+'</div>');
return $div;
}
},
Than create a function that will be run every 10 seconds and make an AJAX request:
function UpdateRes(){
$.ajax({
url: 'Actions.php?action=update',
type: 'post',
data: '&kiu='+$kiu,
}).success(function(data) {
var jsondata = JSON.parse(data);
$.each(jsondata.Records, function(i, item) {
$('.jtable tr.jtable-data-row').each(function(){
if($(this).attr('data-record-key')==item.id){
$(this).find('div').html( item.reservations );
}
})
});
});
}
window.setInterval(function(){
UpdateRes();
}, 10000);
Let your JSON response look like this:
{"Result":"OK",
"Records":
[
{"0":"111","id":"111","1":"20","reservations":"20"},
{"0":"127","id":"127","1":"20","reservations":"20"},
{"0":"133","id":"133","1":"20","reservations":"20"},
{"0":"134","id":"134","1":"20","reservations":"20"},
{"0":"135","id":"135","1":"20","reservations":"20"},
{"0":"326","id":"326","1":"20","reservations":"20"}
]}
And in the end in Actions.php make your query in try catch:
else if($_GET["action"] == "update")
{
//Get records from database
$result8 = mysqli_query($con,
"SELECT l.id,(l.max-l.reserviert) as reservations
FROM td_res l WHERE
l.kiu='" . mysqli_real_escape_string($con,$_POST["kiu"]) . "';");
//Add all records to an array
$rows8 = array();
while($row8 = mysqli_fetch_array($result8))
{
$rows8[] = $row8;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows8;
print json_encode($jTableResult);
}

AJAX and PHP making like button

I have this like button code I want the like number to go up after click but there a need to refresh the page how can I do this:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('body').on( 'click' , '.votebutton' , function(){
var span = $(this).children('span');
var no = parseInt($(this).text(), 10);
$(span).text(++no);
var _id = $(this).data('vote');
$.ajax({
type: 'POST',
url: 'vote.php',
data: {
id: _id
}
});
});
});
</script>
<?php
$q = mysql_query("SELECT * FROM vote");while($row = mysql_fetch_array($q)){
$item[] = $row;
foreach($item as $i){}
echo "<button class='votebutton' data-vote='".$row[0]."'>Up vote</button><span>".$row[1]."</span>";
}
?>
It seems like you have two options. You could either A) make the post request return the new like count; or B) increment it manually with jQuery, which would be faster but not necessarily as accurate.
For the first option, you'd change your AJAX request to something like
$.ajax({
...
}).done(update_count)
where update_count is a function that takes the request as an argument and updates the count for a button. This method is is slower, but it would show an accurate like count at every instance, since the shown value is always the most current value in the database.
For the second option, you could select the span for the button and update its value with jQuery. This would be slightly faster, since it wouldn't have to wait for the AJAX query to complete, but it would only increment once, even if somebody else hit the "like" button.
Use location.reload(); to refresh the page.

AJAX update to multiple database tables

I have an ajax table that reads data from two mysql tables, the tables are
project_ownerships - id_own, project, code, own_current, own_future
projects - id, project, location, type, type2, area, transport, stage
the data reads into the web page table fine, using a join table sql query.
$query_value = isset($_GET['value']) ? $_GET['value'] : "";
$sql = "SELECT project_ownerships.*, projects.*
FROM project_ownerships, projects
WHERE project_ownerships.project = projects.project
AND project_ownerships.code = $query_value'";
$result = $mysqli->query($sql);
however I can't get the edit update working properly. I am only able to get a data - id value from one db-table.
so any updates that belong to projects table update fine, but any updates to project_ownerships do not have the correct id value and update the wrong db-record
here's the update function. this function returns the error "column not found with index or name id_own"
$.ajax({
url: 'update_multi.php',
type: 'POST',
dataType: "html",
data: {
tablename: editableGrid.getColumnName(columnIndex) == "own_current" ? "project_ownerships" : "projects",
id: editableGrid.getColumnName(columnIndex) == "own_current" ? editableGrid.getValueAt(rowIndex, editableGrid.getColumn("id_own")) : editableGrid.getRowId(rowIndex),
newvalue: editableGrid.getColumnType(columnIndex) == "boolean" ? (newValue ? 1 : 0) : newValue,
colname: editableGrid.getColumnName(columnIndex),
coltype: editableGrid.getColumnType(columnIndex)
},
success: function (...,
error: function(...,
async: true
});
here's the php update
$tablename = $mysqli->real_escape_string(strip_tags($_POST['tablename']));
$id = $mysqli->real_escape_string(strip_tags($_POST['id']));
$value = $mysqli->real_escape_string($_POST['newvalue']);
$colname = $mysqli->real_escape_string(strip_tags($_POST['colname']));
$coltype = $mysqli->real_escape_string(strip_tags($_POST['coltype']));
$id_column = "";
if ($tablename == "projects") {$id_column = "id";} else {$id_column = "id_own";}
if ( $stmt = $mysqli->prepare("UPDATE ".$tablename." SET ".$colname." = ? WHERE ".$id_column." = ?")) {
$stmt->bind_param("si",$value, $id);
$return = $stmt->execute();
$stmt->close();
}
basically what I am trying to do....
if projects.id is removed from the sql the update will not work
if project_ownership.id_own is changed to project_ownership.id and projects.id is removed the update will work, but only with project_ownership.* fields
so... I need a column in the sql query called *.id
separately, when an update is sent, the correct table name can be selected by
tablename: editableGrid.getColumnName(columnIndex) == "own_current" ? "project_ownerships" : "projects",
so using the same logic
id: editableGrid.getColumnName(columnIndex) == "own_current" ? editableGrid.getValueAt(rowIndex, editableGrid.getColumn("id_own")) : editableGrid.getRowId(rowIndex),
firstly, recognises that own_current is there, and passes the argument to editableGrid.getValueAt(rowIndex, editableGrid.getColumn("id_own")) but the error returned is "no column found with the id_own name"... ?
I am really confused..
it cannot not be there (removed from the sql) otherwise the update just freezes
but when it is there it cannot be found...
any help would be great
how is it possible to define the ajax - data - id column or the rowIndex column ?
I am working on the theory that
editableGrid.getRowId(rowIndex)
could be the something like (which it's obviously not otherwise this would work)
editableGrid.getValueAt(rowIndex, editableGrid.getColumn("id_own"))
but I have also tried, amongst others
editableGrid.getValueAt(rowIndex, editableGrid.getColumnIndex("id_own"))
which returns "invalid column index -1"
and
editableGrid.getValueAt(rowIndex, editableGrid.getColumnName("id_own"))
UPDATE
there's a couple private functions in editablegrid that define what row id is. so I guess that makes it an editablegrid question and not really a javascript, ajax, or php question suitable for here
You should rename "id" column of each table in your SQL query with AS operator so they dont conflict.
For example :
SELECT B.*,A.name,A.id as author_id FROM BOOKS B
INNER JOIN AUTHORS A ON A.id=B.authorid

Categories