Load More from Php Array - javascript

How is it possible to make load more from array if you scroll to the bottom of the page.
So there are only the first 5 "items" shown and if you scroll to the bottom the next 5 are shown so the browser doesnt chrashes.
My Array:
$statement = $pdo->prepare("SELECT * FROM actvt");
$statement->execute();
$users = $statement->fetchAll();
foreach($users as $row) {
echo $row("username");
}

php
function callMore(){
$last_appt = $_POST['last_result'];
$statement = $pdo->prepare("SELECT * FROM actvt WHERE date = ".$last_appt." limit = X "); //not sure your table structure , X is how many you want to load
foreach($statement as $val){
//Set your gathered results here
}
return X //return the results to your ajax call
}
js / ajax call
$.ajax({
type: 'POST',
data: {
action: 'callMore',
lastPost : XXXX //Put your last post here
},
success : function(msg){
//Do something with returned data append where ever
},
datatype: 'json',
});
From here you will need to detect when you have reached the last post... I recommend doing a detection of when you are at the bottom of the page, if you are using jquery use scrollTop on the last post, to find its Y value, and then window offset with scroll to trigger if you are close to reaching the bottom.. ONce you have reached the bottom, run your ajax function and retrieve the next results.

so you may create sth like a load.php:
$start=$_GET["page"]*100;//100 entries
$statement = $pdo->prepare("SELECT * FROM actvt ");
$statement->execute();
$users = $statement->fetchAll();
$counter=0;
foreach($users as $row) {
$counter++;
if($counter>$start && $counter <=$start+100){//100 entries
echo $row("username");
}
}
if($counter<$row.length){
echo "<a href='?page=".($page+1)."'>Next Page</a>";
}
Now you can call "http://yourpage?page=10"...
The js part is enough to fill another answer...

Related

JQuery Ajax Mysql data retrieval getting extra carriage returns and appearing in textarea

I have a bit of a mystery. I've done code like this several other times with expected results, but this time it is behaving oddly.
The text coming from the Mysql database through AJAX to the main calling program is getting 3 extra carriage or line returns and each time I display it, it adds these unwanted line returns to the textarea box for further editing.
The steps:
1. Store textarea content to database. Example data could be: 'The fox jumped high'
2. Retrieve the data and display in another textarea box for editing
3. The textarea shows the retrieved text, but has extra 3 line returns.
My Storage Call: main program
$(document).on('click', '#submit2', function(){
event.preventDefault();
var comment = $("#comment2x").val();
update = 'yes'//chooses to update not insert new
console.log(comment);
$.ajax({
url:"/modules/feedback/feedback_ajax.php",
method:"POST",
data:{action:'save',
user_id:user_id,//global variable set at beginning
comment:comment,
details:details,
tab:tab,
update:update,
feedback_id:feedback_id
},
success:function(data){;
//console.log(data);
$('#comment2x').val('');//clear text area
$(window).scrollTop(scroll_position);
}
});
});
The SQL Update Code: feedback_ajax.php
if($_POST['action']=='save'){
$user_id = $_POST['user_id'];
$comment = $_POST['comment'];
$details = $_POST['details'];
$tab = $_POST['tab'];
$update = $_POST['update'];//'yes' = update existing entry, 'no' = insert new entry
$feedback_id = $_POST['feedback_id'];
//insert into database
$sql = "INSERT INTO feedback (user_id,comment,details,tab,status) VALUES (?,?,?,?,?)";
$db->prepare($sql)->execute([$user_id,$comment,$details,$tab,'New']);
I look in the database using phpMyAdmin and it shows no extra spaces or line returns.
My AJAX Call: main program
$.ajax({//get raw comment from database
url:"/modules/feedback/feedback_ajax.php",
method:"POST",
data:{action:'get_raw_comment',feedback_id:feedback_id},
success:function(data){
console.log('EDIT');
console.log(data);
$('#comment2x').val(data);
$("#comment2x").height( $("#comment2x")[0].scrollHeight );//adjusts height of textarea to fit text
}
});
The other end returning the data: feedback_ajax.php
if($_POST['action']=='get_raw_comment'){
$feedback_id = $_POST['feedback_id'];
$sql = "SELECT comment FROM feedback WHERE feedback_id=".$feedback_id;
$stmt = $db->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
$comment = $row['comment'];
echo $comment;
}
I use Xdebug and the variable $comment shows NO extra spaces or line returns.
In the Ajax call, console.log(data); shows the data returned - the Chrome console shows extra line returns!!!
When the AJAX success call $('#comment2x').val(data); places it in the textarea, the textarea shows extra line returns - 3 to be exact.
The HTML for the textarea is:
<textarea class="form-control" name="article" id="comment2x"></textarea>
What more can I do to troubleshoot this and eliminate these extra line returns showing up?
return data from feedback_ajax.php in json format as follows:-
$result = array();
if($_POST['action']=='get_raw_comment'){
$feedback_id = $_POST['feedback_id'];
$sql = "SELECT comment FROM feedback WHERE feedback_id=".$feedback_id;
$stmt = $db->prepare($sql);
$stmt->execute();
$result['success'] = $stmt->rowCount();
if($result['success'])
$row = $stmt->fetch();
$result['comment'] = $result['success'] ? $row['comment'] : "";
}
echo json_encode($result);
receive data in json format and proceed
$.ajax({//get raw comment from database
url:"/modules/feedback/feedback_ajax.php",
method:"POST",
dataType: 'json', //IMPORTANT TO RECEIVE DATA IN JSON
data:{action:'get_raw_comment',feedback_id:feedback_id},
success:function(data){
if(data.success)
{
$('#comment2x').val(data.comment);
$("#comment2x").height( $("#comment2x")[0].scrollHeight );//adjusts height of textarea to fit text
}else
{
console.log(data); //to check what data coming
}
}
});
Just thought I would post my Json version which solved the problem:
Mysql data retrieval code:
if($_POST['action']=='get_raw_comment'){
$result = array();
$feedback_id = $_POST['feedback_id'];
$sql = "SELECT comment FROM feedback WHERE feedback_id=".$feedback_id;
$stmt = $db->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
$comment = $row['comment'];
$result['comment']=$comment;
echo json_encode($result);
}
Ajax code:
$.ajax({//get raw comment from database
url:"/modules/feedback/feedback_ajax.php",
method:"POST",
dataType: 'json',
data:{action:'get_raw_comment',feedback_id:feedback_id},
success:function(data){
console.log(data);
$('#comment2x').val(data.comment);
$("#comment2x").height( $("#comment2x")[0].scrollHeight );//adjusts height of textarea to fit text
}
});

Why my php array return only recent/last post activities

I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json_encode for append it.
Jquery sent two type data to php file:
1st: page id
2nd: post ids (a jquery array sent them to php file)
If I used print_r($_REQUEST['CID']); exit; on php file for test what he get from jquery, Its return and display all post ids well.
But if I make any reply on particular post, Its only return recent post reply.
That means, if I have 3 post like: post-1st, post-2nd, post-3rd ; my php return only post-3rd activities.
I want my script update any post reply when it submitted at sql.
my wall.php
// id is dynamic
<div class="case" data-post-id="111"></div>
<div class="case" data-post-id="222"></div>
<div class="case" data-post-id="333"></div>
//Check for any update after 15 second interval by post id.
<script type="text/javascript" charset="utf-8">
var CID = [];
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});
function addrep(type, msg){
CID.forEach(function(id){
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>");
});
}
var tutid = '<?php echo $tutid; ?>';
function waitForRep(){
$.ajax({
type: "GET",
url: "/server.php",
cache: false,
data: {
tutid : tutid,
CID : CID
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(
waitForRep,
15000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(
waitForRep,
15000);
}
});
}
$(document).ready(function(){
waitForRep();
});
</script>
server.php (may be problem in my array or something else)
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
} // array close
$rows = mysqli_fetch_assoc($res);
$row[] = array_map('utf8_encode', $rows);
$data = array();
$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
Try to declare CID array like this:
var CID = new Array();
It looks like you're looping through the CIDs and running an SQL query for each one, but you're only retrieving the results once, outside of the loop. You'll only get the last query's results if you run
$rows = mysqli_fetch_assoc($res);
outside of the CIDs foreach loop.
#koc:
Unfortunately, it won't be as simple as moving the closing loop bracket. If you're trying to retrieve multiple datasets in one AJAX call, then you'll need to handle multiple datasets in your AJAX's success callback, or in your addrep() function. Here's one way to do it, but you can do it many different ways depending on what you're ultimately trying to do:
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
$data = array();
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"
SELECT *
FROM comments_reply
WHERE post_id =".$value."
AND qazi_id=".$_REQUEST['tutid']."
AND date >= '$datetime'
ORDER BY id DESC LIMIT 1
") or die(mysqli_error($dbh));
$row = mysqli_fetch_assoc($res)
$data[] = array_map('utf8_encode', $row);
} // array close
//$rows = mysqli_fetch_assoc($res);
//$row[] = array_map('utf8_encode', $rows);
//$data = array();
//$data['id'] = $rows['id'];
//$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
then in your Javascript:
...
success: function(data){
for (var i=0, len=data.length; i<len; i++) {
addrep("postreply", data[i]);
}
setTimeout(waitForRep, 15000);
},
...
But again, that's just an example. I don't really know what your datasets look like or how you want the data to be passed around and used. This is just an idea that hopefully gets you going in the right direction.

PHP, AJAX, and server-client frustrations

I have a table that's generated from php. The way I've done this is probably not the most efficient way to do it since I wrote it all myself and I'm not an expert.
Everything starts when the user pastes part numbers into a search box on a previous page, which is then sent here to return.php under the variable lines.
return.php
$c = $_POST['c'];
if (!$_SESSION['lines']) {
$_SESSION['lines'] = $_POST['lines'];
}
$partNumber = array(); //define $partNumber as array
$x = -1;
$supplierQuery = "SELECT distinct supplier, quotePartNumber FROM allparts WHERE quotePartNumber = '$q'" ;
$supplierResult = mysqli_query($con, $supplierQuery);
foreach ($_SESSION['lines'] as $q) {
$x = $x + 1; // each time we loop through this, x++
while ($row = mysqli_fetch_array($supplierResult)) {
$partNumber[] = $row['quotePartNumber'];
$customerQuery = "SELECT DISTINCT quoteCustomer FROM $supplier where quotePartNumber = '$q'";
if (!$c) { // $c becomes set once a user types in an end customer - without that, we want ALL generic info to be returned.
$costQuery = "SELECT * FROM $supplier where quotePartNumber = '$partNumber[$x]' ORDER BY quoteCost ASC LIMIT 1" ;
} else {
$costQuery = "SELECT * FROM $supplier where quotePartNumber = '$partNumber[$x]' and quoteCustomer = '$c' ORDER BY quoteCost ASC LIMIT 1" ;
}
$getCustomer = mysqli_query($con, $customerQuery);
}
later on in my table, I have this:
<td><?= $partNumber[$x] ?></td>
<td><?= $cost ?></td>
<td>
<select class="btn btn-danger" onChange="selectCustomerCMR(this.value)">
<option value="" disabled selected><?php if($c) { print $c; } else { print "Select Purchasing Customer";} ?></option>
<?php
while ($row = mysqli_fetch_array($getCustomer)) {
$customerName = $row['quoteCustomer'];
?>
<option><?= $customerName ?></option>
<?php
}
?>
</select>
</td>
Any change to the dropdown will launch this script:
<script>
function selectCustomerCMR(str) {
var id = str;
$.ajax({
type: 'POST',
url: 'return.php',
data: {'c':id,'lines':lines},
success:function(data){
$("#info").html(data);
}
});
}
</script>
What I'm trying to do
Let's say my generated table has 3 rows, with part numbers
There is a drop-down to allow the user to select a specific customer. When the user clicks on this, the script takes that value and uses AJAX to send it back to the same page (return.php), which then grabs it using the $c = $_POST['c']; code.
My Issue
When return.php loads a "second time" with a value for $c, I don't know how to make it so that the line that the user selected gets changed. Right now, anytime I select a customer from a line's drop-down, return.php reloads, and it assigns that customer to the FIRST row, ignoring all the other rows.
I specifically created $partNumber as an array and used $x so I could increase the value of x each time the foreach loop iterated. This worked, so of the three lines in the above table, the first one is $partNumber[0] and the second one is $partNumber[1], etc... But I don't know how to get that information into the javascript function and send it back to the page when it reloads, so that I can then change my SQL query to ONLY action when the condition is right for that line...
Thanks for reading, and thanks for any help!
Consider changing your <select> code to this:
<select class="btn btn-danger" data-x="<?= $x ?>" onChange="selectCustomerCMR(this)">
Then, your Ajax code can be changed to this:
function selectCustomerCMR(select) {
var id = select.value, x = select.getAttribute("data-x");
$.ajax({
type: 'POST',
url: 'return.php',
data: { c: id, lines: lines, x: x },
success: function(data){
// Update!
}
});
}
That way, your PHP can get both c and x.

Pass PHP variable to ajax and run PHP function based on that variable

I have Database records which are loop echoes out, so it lists down in Divs each records info.
I'm trying to make a delete button, to delete the specific record from this page view. The loop number tracker variable $i also corresponds to the record ID, so loop 3 outputs a div containing the info of record ID 3.
So I just need to on click pass $i to a PHP function to then run the sql to drop the record with ID $i.
I'd like to do this all on the same page so I'm assuming I need ajax but thats where I get stumped. Also so I can have an alert "Are you sure" I've done ajax with jquery to ajax to php, but never this way.
PHP:
$webserver = 'localhost';
$administrator = 'root';
$password = '';
$db_name = 'cdb';
$db = mysqli_connect($webserver, $administrator, $password, $db_name)
or die('Error connecting');
if( isset($_REQUEST['page']))
{
$_SESSION['page'] = $_REQUEST['page'];
}
else
{
$_SESSION['page'] = 1;
}
$records_per_page = 8;
$query = " SELECT *
FROM cars, users
WHERE cars.dealerID = users.dealerID
AND users.username = '".$_GET['username']."'";
$result = mysqli_query($db, $query)
or die("Error in query: '$query'");
$row = mysqli_fetch_assoc($result);
$i = 1;
$start = ($_SESSION['page'] - 1) * $records_per_page;
$end = ($_SESSION['page']) * $records_per_page;
while($row = mysqli_fetch_assoc($result) and $i < $end)
{
$i++;
if( $i > $start )
{
<div>
delete
</div>
<div of magic n' fairies>
echo $row['informationandstuff'];
</div>
}
}
Delete function:
function deleteCar()
{
$delete = "DELETE FROM cars
WHERE carindex = '".$i"'";
}
I could post $i to another file and do it bt would prefer to keep to same page and allow for an are you sure js pop up.
If I'm understanding you correctly, one way to do this would be to store the $i variable in either an html data attribute, or an id (as you suggested). Then, use jquery to collect that id and pass it to the data property in the ajax call.
Sample list item (I'm assuming a heredoc here):
<div class="list-item" data-record-id="{$yourId}">your output</div>
Now, collect the id that the user clicked:
$('.list-item').click(function(){
//get item id
var recordId = $(this).data('record-id');
deleteRecord(recordId);
});
function deleteRecord(recordId) {
var recordData = 'recordId=' + recordId;
var request = $.ajax({
type: "post",
url: "the-php-page-you-use-for-async-calls",
data: recordData,
success: function(resp){
//show some validation that the record has been deleted
}
});
}

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

Categories