I am using AJAX to loadmore data from an image gallery.
I pass PHP variable to set the $page number and other data. Each time I loadmore data from AJAX, I would like the $page to increase by 1 so next time, it gets the next data on the list. Here is my JS
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight) {
$('div#loadmoreajaxloader').show();
$.ajax
({
url: "loadmore.php",
method: "get",
data: { page: "<?=$page?>", perpage: "<?=$perpage?>"},
success: function(html)
{
if(html)
{
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
// ###### THIS IS NOT WORKING
<? $page++; ?>
}
else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
}); // close AJAX
} // close if()
}); // close $(window)
I tried incorporating <? $page++; ?> in the success function, but it's not working.
I USE THE $page variable inside my SQL query
HERE IS MY loadmore.php CODE
if (isset($_GET['page']))
{
$page = $_GET['page'];
$perpage = $_GET['perpage'];
$start = ($page -1) * $perpage ;
$sql = mysql_query("select * from ..... limit ".$start.", ".$perpage." ");
$html = '';
while($blog2 = mysql_fetch_array($sql))
{
$html .='HTML GOES HERE';
}
echo $html;
exit;
}
What I'm trying to achieve is to load the SQL query starting from the next page every time I load more data... Any suggestions on how I should proceed?
First, remember to sanitize any user input in your PHP file to prevent sql injection:
$page = $_GET['page'];
$perpage = $_GET['perpage'];
// escape the values, or make sure they are numbers, e.g.:
if(!is_numeric($page))
$page = 0;
if(!is_numeric($perpage))
$perpage = 10; // or whatever default value
And write your PHP values into Javascript variables and use those in your js code:
var pageNumber = <?= $page ?>;
var perPage = <?= $perpage ?>;
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight) {
$('div#loadmoreajaxloader').show();
$.ajax
({
url: "loadmore.php",
method: "get",
data: { page: pageNumber, perpage: perPage},
success: function(html)
{
if(html)
{
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
// use the js variable
pageNumber++;
}
else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
}); // close AJAX
} // close if()
}); // close $(window)
No
PHP runs server-side, the AJAX runs client side. You need a javascript variable there (although you can set its initial value with PHP).
Related
I am displaying ajax likes on number of posts but the problem is that when i click 'like button' the likes (without loading the page) display on first post only and when i refresh the page all the likes display on their own places.
I want to show ajax like on the particular post not on only the first one. I guess i need to pass the ID in success function but i do not know how. Here is the code.
In my code: a Rumor is a post, Like = approve, dislike = disapprove.
View Ajax + That Particular part of Html View
function approve_rumor(r_id) {
// alert("dfdfdf");
$.ajax({
type: "post",
url: "<?php echo base_url('Home1/approve_rumor') ?>",
data: {
r_id: r_id
},
cache: false,
success: function(val) {
if (true) {
$('#showapp').html(val);
} else {
// <?php //echo base_url('Login'); ?>;
alert("You need to Login");
}
}
});
}
<span class="like-listing fll approve" onclick="approve_rumor(<?php echo $rumors->rumor_id; ?>)">
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
</span>
<span id="showapp" class="fll"><?php echo $rumors->rumor_totalapprovals ?></span>
Controller
function approve_rumor() {
if ($this - > session - > userdata('user_email', 'user_id')) {
$this - > load - > model('rumor_model');
$r_id = $this - > input - > post('r_id');
$data['user_id'] = $this - > session - > userdata('user_id');
$data['rumor_id'] = $r_id;
$this - > rumor_model - > ApproveRumor($data);
//$this->load->view('home1',['approval'=>$approval]);
} else {
return redirect('Login');
}
}
function ApproveRumor($data) {
// echo "<pre>";
// print_r($data);
// exit;
$r_id = $data['rumor_id'];
$query = $this - > db - > insert('approval', $data);
if ($query) {
$a = $this - > db - > query("SELECT * , count(rumor_id) as count_like FROM approval WHERE rumor_id = $r_id ");
echo "<pre>";
print_r($a - > row() - > count_like);
$totalapprovals = $a - > row() - > count_like;
$this - > db - > query("UPDATE rumors SET rumor_totalapprovals = $totalapprovals WHERE rumor_id = $r_id");
// echo $totalapprovals;
// $this->db->where('rumors.rumor_id',$r_id);
// $res = $this->db->update('rumors',$totalapprovals);
} else {
echo "0";
}
}
A cool way I've found to pass data through to the $.ajax callback function is adding a custom option and then referencing it in the $.ajax callback as this.optionProp:
$.ajax({
type: "post",
url: "your/url/here",
data: {
r_id: r_id
},
r_id:r_id, //Your custom option
cache: false,
success: function(val) {
console.log("r_id: " + this.r_id); //The custom option can be referenced with this.optProp
}
});
Let me know if this helps or is not what you are looking for and we'll get it fixed
You need to return an object from your server side function that has an id attribute so you can call it after success like this:
function approve_rumor(r_id) {
// alert("dfdfdf");
$.ajax({
type: "post",
url: "<?php echo base_url('Home1/approve_rumor') ?>",
data: {
r_id: r_id
},
cache: false,
success: function(val) {
var id = val.id; //gets the id attribute from the returned val Object
}
});
}
I have a function that populates the DataTable when the document is ready.
$(document).ready(function()
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php',
"dataType": "json",
"bDestroy": true,
"stateSave": true
});
// this portion reloads the datatable without refreshing the page
setInterval(function() {
$dataTable.ajax.reload();
}, 60000);
}
So now I want to add a search feature. It would basically re-populate the DataTable with the search data returned from the server.
Directly below is the jQuery that retrieves the parameters entered by the user:
$('#searchSubmit').on('click', function()
{
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
$.ajax({
url:'api/qnams_all.php',
type:"POST",
data:{searchbooking: searchbooking, searchquote: searchquote},
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
dataType:"json"
}).done(function(response){
console.log(response.data)
}).fail(function(){
alert('error');
}).always(function(){
alert('done');
});
});
Here is the PHP process found in api/qnams_all.php:
<?php
include("../include/database.php");
include("../include/sessions.php");
$_SESSION['where'] = "";
$searchbooking = strip_tags(mysqli_real_escape_string($dbc, trim(strtoupper($_POST['searchbooking']))));
$searchquote = strip_tags(mysqli_real_escape_string($dbc, trim(strtoupper($_POST['searchquote']))));
// build the WHERE clause
if($searchbooking != ""){
$_SESSION['where'] = "booking = '".$searchbooking."'";
}
if($searchquote != ""){
if( $_SESSION['where'] != "" )
$_SESSION['where'] .= " AND ";$_SESSION['where'] .= "quote = '".$searchquote."'";
}
// check if WHERE is blank
if($_SESSION['where'] == ""){$where = "where TLI_COMPLETE = 'N'";}
else{$where = $_SESSION['where'];}
// run the query
$select = "SELECT
CONCAT('\"',COALESCE(booking,''),'\"')
,CONCAT('\"',COALESCE(quote,''),'\"')
FROM
searchTable " . $where . "";
$query = mysqli_query($dbc, $select) or die(mysqli_error());
$resnum = mysqli_num_rows($query);
echo "{\"data\":[";
$i = 1;
while($row = $query->fetch_assoc())
{
echo "[";
echo implode(', ', $row);
echo "]";
if($i < $resnum){
echo ",";
}
$i++;
}
}
echo "]}";
mysqli_free_result($query);
?>
The PHP process above works perfectly with the $(document).ready() function.
My question is: how can I manipulate my code so that the search functions works with the ready() function?
Right now, the search function is located outside of the ready() function. Can I apply the search function within the ready() function? If so, how would the AJAX call look like?
Currently, it reads:
"ajax": 'api/qnams_all.php'
If I am able to add the search to the ready() function, would this AJAX call change?
To put it in one question, how can I add the search feature to the ready() function so that I can initially display data, and then repopulate the data if the user decides to search for a record?
You have to keep 2 copies of the same code(ajax part)
In document.ready with async:false in ajax call.(Will load the search results when the page opens).
The original place where it is now i.e inside the onClick function.(For the default behaviour).
That's because you need to wrap your ajax call in an eventListener and here you are having to separate events.
I want to load more than 10 rows from my table with jQuery, but it's not working.
My php code: (...chat.php?load=archive)
} else if (isset($_GET["load"]) && $_GET["load"] == "archive") {
echo "<script type='text/javascript' src='includes/js/chatArchive.js'></script>";
$limit = (int)$_POST["limit"];
$result = mysql_query("SELECT * FROM `chat` ORDER BY `date` DESC LIMIT ".$limit.", 2");
if (mysql_num_rows($result)) {
while($db = mysql_fetch_array($result)) {
echo "..."; // My datas...
}
echo "<div style='text-align: center; margin: 10px 0 10px 0;'>\n";
echo "<input type='submit' value='Load more rows' class='loadMore'>\n";
echo "</div>\n";
}
}
My JS file: (chatArchive.js)
var limit = 50;
$(document).ready(function() {
$(".loadMore").click(function() {
limit += 10;
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
type: "POST",
data: { "limit" : limit },
success: function() {
alert("Success...");
console.log(limit); // This displayed my console!!!
}
});
});
});
Can anyone point out the problem?
Function which is defined as a callback for success property has an argument, usually called data, which is the returned value from your script. So, you should change your success function as follows:
success: function(data) { // see data here
alert("Success...");
console.log(limit); // This displayed my console!!!
console.log( data ); // check what data contains
}
Also it's a good practice to add error callback, which will indicate that something bad happens:
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
....
error: function() {
alert("Bad thing happenned!");
}
)};
your ajax method is POST but in your php script you check GET request
if (isset($_GET["load"]) && $_GET["load"] == "archive")
Change Your ajax method to GET
I am trying to change text in a div depending on value change on a dropdown box. The dropdown box values are populated from MySQL using PHP. I am loading the dropdown box on page load.
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response)
{ alert("The winner was passed!")},
}
);
<?php
require_once 'config.php';
$iid=$_GET['winner_id'];
$sql="SELECT * FROM Products where prod_id = ".$iid;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$prodCredit="Credit :".$row["prod_price"];
$time="estmated time is :".$row["prod_time"];
?>
$('#esdTime').text(' <?php echo $prodCredit ?> ' );
$('#credit').text(' <?php echo $time ?> ' );
});
});
</script>
I am not getting results.
Let me know how can I assign JavaScript value idval to PHP variable $iid value.
//you would want a the php script to be in a separate file that you could call Have the php file return an array or json object. Have the callback success function append the new options to the html select. The following is a ruffexample
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response){
for (var i = 0; i < response.length; i++) {
$("#idofyourselect").append("<option val='" +response[i]+"'>" + response[i] + "</option>");
}
},
}
);
</script>
I have a table in which the details are fetched from the DB.
if(mysql_num_rows($sql) > 0)
{
$row_count_n=1;
while($rows=mysql_fetch_assoc($sql))
{
extract($rows);
$options1 = select_data_as_options("project_resources", "name", $resource_allocated);
$options2 = select_data_as_options("project_roles", "name", $role);
echo "<tr>";
echo "<td><select name='ra_$row_count_n'><option value=''>-- Select --$options1</option></select></td>";
echo "<td><select name='role_$row_count_n'><option value=''>-- Select --$options2</option></select></td>";
echo "<td><input type='text' name='start_date_tentative_$row_count_n' class='date_one' value=$tentatively_starts_on /></td>";
echo "</tr>";
$row_count_n++;
}
}
I wanted to update the table when required, am doing this using Ajax by collecting data from the form using Jquery and saving it on button click.
$("#save_changes_id").click(function()
{
// To retrieve the current TAB and assign it to a variable ...
var curTab = $('.ui-tabs-active'); // in NEWER jQueryUI, this is now ui-tabs-active
var curTabPanelId = curTab.find("a").attr("href");
if(curTabPanelId == "#tab_dia")
{
var curTab = $('#sub_tabs .ui-tabs-active');
var curTabPanelId = curTab.find("a").attr("href");
}
responseData = doAjaxCall($(curTabPanelId + " form"));
if(responseData == 1)
showMessage('status_msg', 'Project details updated successfully', 'green');
else
showMessage('status_msg', 'Error: Please check all the fields', 'red');
});
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
responseData = data;
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
Ajax code is as below:
case "allocate_ba_details":
for($i=1; $i<=$row_count; $i++)
{
$resource = $_REQUEST["ra_$i"];
$role = $_REQUEST["role_$i"];
$start_date_tentative = $_REQUEST["start_date_tentative_$i"];
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id = $pdid"));
if($already_available_check > 0)
{
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid");
}
}
echo $sql;
break;
As I am new to this am not sure how to pass the row name in order to update a particular row.
Please suggest a solution. Thanks in advance.
firstly use PDO or some php framework that has nice API to work with mysql. Second don't use success/error callback in jquery is too deprecated. Instanted use done/fail.always.
I understand that you want update row in html table data from the server ?
In success callback simply update the table using jquery text method for jquery object. You don't paste all code so i write example:
in server.php
<?php
[...]
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id =" . intval($pdid)));
[...]
echo $already_available_check;
?>
This code return the integer, so in doAjaxCall:
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
if(typeof data !== 'undefined' && $.isNumeric(data)) {//check that server send correct anserw
$('whereIsData').text(data);
}
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
}
Now in success method you populate some DOM element using text method. You cannot simply return data from ajaxCall method because $.ajax is asynchronized method and responseData has value only when ajax request ends, so always return undefined in you example. You must present responseData to the user in success callback method.
For one thing...
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid")
needs single quotes around $pdid
Also don't echo the $sql. Instead do your inspection and form a response.
$response = array();
if(EVERYTHING_IS_GOOD){
$response['status'] = 'good to go';
}else{
$response['status'] = 'it went horribly wrong';
}
echo json_encode($response);