I hav this code in jquery which is written in such a way that when i scroll down my mouse next set of records are fetched from db and displayed. Initially my page shows 25 records, and when i scroll down next 15 records r fetched from db. My problem is that i am not able set a counter and increment the counter whenever scroll function is called. And also when ever i scroll down same 15 records r displayed.
This is my code...
$(window).on('scroll',function(){
if($(window).scrollTop()==($(document).height()-$(window).height())){
$.ajax({
type: 'POST',
url: 'getdata.php',
success: function(nxt_data){
$('#data').append(nxt_data);
}
});
}
});
Create a page variable and then add to it everytime the ajax is called.
var page = 1;
$(window).on('scroll', function () {
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
page++;
$.ajax({
type: 'POST',
data: 'page=' + page,
url: 'getdata.php',
success: function (nxt_data) {
$('#data').append(nxt_data);
}
});
}
});
Your issue appears to be because getdata.php has no way of knowing what records to return, so it is just returning the same 15 rows.
var counter=25;
$(window).on('scroll',function(){
if($(window).scrollTop()==($(document).height()-$(window).height())){
$.ajax({
type: 'GET',
url: 'getdata.php?start_row=' + counter,
success: function(nxt_data){
$('#data').append(nxt_data);
counter += 15;
}
});
}
});
In your PHP file you can access the counter variable using $_GET['start_row'];
Related
i am doing a social media project via udemy. the instructor has done ajax for infinite scrolling.the ajax part.i am having doubts regarding it in some lines.
NOTE-posts_area is an empty div where we are going to load the posts
explanation of the $(window).scroll(function() ???
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
//$.ajax is a jquery to perform ajax request
$.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn, //what does this mean ???
cache:false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);//post area is a empty div created to enter the posts
}
});
$(window).scroll(function() {
var height = $('.posts_area').height();
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { //if noMorePost is true this wont execute aka there are posts to be loaded
$('#loading').show(); //show loading gif while more posts are loaded
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn, //whatever page we are set to
cache:false,
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nomoreposts
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
the ajax file
<?php
include("../../config/config.php"); //has mysql connection variable
include("../classes/User.php");
include("../classes/Post.php");
$limit=10; //no of posts to be loaded per call(we dont want everthing to load at the same time)
$posts=new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST,$limit);
?>
what does the following statements do ??
data: "page=1&userLoggedIn=" + userLoggedIn
$('.posts_area').html(data);
Comments added to your code should hopefully explain each step.
$(window).scroll(function() {
//get the height of the area that you are wanting to use infinite scroll on (doesn't appear to be used.....)
var height = $('.posts_area').height();
//see how far down you have scrolled (doesn't appear to be used.....)
var scroll_top = $(this).scrollTop();
//look for an element with class 'nextPage' and get it's value (weird way of doing it - would guess the value is a URL
var page = $('.posts_area').find('.nextPage').val();
//see if class noMorePosts exsits in posts_area -> will return false if it does not.
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
//the function we are in is called every time the user scrolls the page.
//this part looks to see if you have scrolled to the bottom of the page (is the total scroll height equal to the amount you have scrolled plus the height of the page) -> if it is (and the 'noMorePosts' class is not found, run the function.
//As a side note the methods used in this example are terrible and prone to lots of errors and problems so just be careful that you don't try and use them in a live website.
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { //if noMorePost is true this wont execute aka there are posts to be loaded
$('#loading').show(); //show loading gif while more posts are loaded
//make ajax call
var ajaxReq = $.ajax({
//url to call
url: "includes/handlers/ajax_load_posts.php",
//type of request
type: "POST",
//as this is a POST request you will send some data -> this is that data, you are sending the page (value defined above) and the userLoggedIn variable (which must be defined elsewhere)
data: "page=" + page + "&userLoggedIn=" + userLoggedIn, //whatever page we are set to
//do not cache the response (so if you ask for the same info the server still processes the request)
cache:false,
//think you should get the rest
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nomoreposts
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End
//calling the scroll function on page load? Also this seems an odd way of doing it but who am I to judge :-P
(window).scroll(function())
step1 batch: (drop down ) in dynamically loaded, after selecting one of the value from dropdown step 2 is loaded by ajax call, in setp 2 when i click on edit button, step 3 is loaded via ajax call again. in step 3 when i click on edit button ajax call is working fine but its not posting the value to php script.
//ajax call
function validateFees(strAddNo) {
var collectFees = $("#collectFees").val();
if(collectFees == "")
{
$("#validateFeesResult").html('<div class="info">Please enter your Fees Amount.</div>');
$("#collectFees").focus();
}
else
{
var dataString = 'collectFees' + collectFees + 'strAddNo' + strAddNo;
$.ajax({
type: "POST",
url: "validateFees_script.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#validateFeesResult").html('Loading...');
},
success: function(response)
{
$("#validateFeesResult").hide().fadeIn('slow').html(response);
}
});
}
}
I'm sure it's extremely simple but I'm not understanding how to do it?
Change the data format as:
var dataString = 'collectFees=' + collectFees + '&strAddNo=' + strAddNo;
Check out : http://api.jquery.com/serialize/
I need to update the user's points on each drop he successfully make, but for some reason the $.ajax call seems to not work as desired...
I am getting the current points using $('#userPoints').val(), then I would like to make each and addition to the current number or set first score - if...else.
Any help?
function Point() {
var phpPoints = $('#userPoints').val();
if (phpPoints != null) {
var Usrpoints = phpPoints + 5;
} else {
var Usrpoints = 5;
}
alert('Points: '+phpPoints);
var sndData = { acts:'Points', points: Usrpoints };
$.ajax({ // begin add ajax
type: "POST",
url: "game/lib/updateGame.php",
dataType:"html",
cache: false,
data: sndData,
success: function(sndData) {
$('div#UpdateUser').html(sndData).fadeIn('slow');
}
}); // end ajax
}
here instead of td use the element in which you are droping
$('td').bind('dropstop', function(){ Point();
});
hi i am working on a codeigniter project. I want to execute a php function after an interval of 10seconds. When a user visits that specific page after 10 seconds i want that php function to be executed. In that php function i have set a counter which adds 1 to the specific table into the database. I have tried using AJAX but didnt get the desired result. Kindly explain me with examples as i am new in ajax. Thanks in advance...
#Majid Golshadi s answer is the right answer.
Working version is here
Please in view that is loaded all the time (like header_view.php)
add this few lines
<script type="text/javascript">
var _baseUrl = "<?= base_url() ?>";
</script>
This makes that your base_url is usable in JavaScript anywhere in page (but make sure to have it somewhere on "TOP" of page)
and literraly use #Majid Golshadi s answer in this way
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: _baseUrl + "/your/controller/param",
type: 'post',
data: {"token": "your_token"}, });
}, 10000);
});
using jquery this will be the easiest and fastest way to do that
`//setting timeout to 3 seconds = 3 thousand milli seconds
setInterval(function(){
//ajax call
$.ajax({
url: _baseUrl + "/controller_name/function_name/", //the url where you want to fetch the data
type: 'post', //type of request POST or GET
data: {"data": "value"}, }); //data passed to controller
},3000);`
in your controller you may use
function function_name(){
$var = $this->input->post();//getting data passed from ajax
//process here...
echo json_encode($var)//parses and returns the processed value
}
try this
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('your/controller/address');?>",
type: 'post',
data: {"token": "your_token"},
});
}, 10000);
Example
in your view
$(document).ready(function(){
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('MyController/Mymethod');?>",
type: 'post',
data: {"token": "12majid18"},
});
}, 10000);
});
and in Your Controller write method like this
public function Mymethod()
{
$token = $this->input->post('token');
if ( $token == '12majid18' )
{
/*call your model and insert your data in Table*/
}
}
you can try this:
window.jQuery(function(){
var y=setInterval(function() {
window.jQuery.post(url,{"token": "your_token"},function(res){
alert(res);
});
}, 10000);
});
i use this script
<script type="text/javascript">
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var boxval = $("#content").val();
var dataString = 'content=' + boxval;
if (boxval == '') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value = '';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click", function () {
var ID = $(this).attr("id");
var dataString = 'msg_id=' + ID;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete_data.php",
data: dataString,
cache: false,
success: function (html) {
$(".bar" + ID).slideUp('slow', function () {
$(this).remove();
});
}
});
}
return false;
});
});
</script>
this script combine live update and delete record using jquery and ajax
the problem is when I refresh the page, the record will disappear .. how to keep records that show up are not dissapear when the page is reloaded?
First Check the comment list. Did you put any limit in query, if so then use Order by Primary ID desc.So it would display latest records first.
When you delete any record, check whether it is actually deleted from database or not. Because you are not checking whether record actually deleted or not as per the code you given.
Assuming you are using update_data.php and delete_data.php to manipulate some database, you could use PHP to render the page initially using the data that is currently on the database.
If that is not the case, and you don't have access to that database (it could be a third party web service, right?), or you don't want to do that for any reason, you could use cookie like Saeed answered.