ajax infinity scroll error some time same result retuen - javascript

i am new to coding and i am writing project for teach me self about PHP social site. In post loading ajax call page number are not updating in start of recall and sometime same result are show again and again. my be add some delay in js script? please help me. Thanks
first part is post class which load post from database and second part is js script.
i check the code again all are fine but i need to delay or reduce ajax call. load is still process and ajax is trigger another call that why it have same page is load again and again.
may be delay in js script require to slow down loading process
script
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
$.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache: false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function() {
var height = $('.posts_area').height(); //Div containing posts
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') {
$('#loading').show();
//alert("hello");
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache: false,
success: function(response) {
$('.posts_area').find('.nextPage')
.remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts')
.remove(); //Removes current .nextpage
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
</script>

i can't really execute your code but you can try to set id_post as attribute for each post you render with js , then next time you get new posts you can know if the post already exists with
document.getElementById('id_post')
if you get an element you don't re-render it.
if its empty you can render your post

Related

Not able to reload the div while using jQuery $.ajax()

I am trying to reload a div with id #todos after the data is saved in the database.
I tried using .load() in $.ajax()
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
},
});
});
The problem with this, that it is not reloading the page but it is updating the data in database correctly.
I also tried this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
In this, it is reloading the page as well as updating the data in the database but the problem is that it only reload and update the data at the first request, and after that I need to reload the whole page to update next data.
I tried to check if I am getting any data or not
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
console.log(data);
},
});
});
It returned nothing, but my data in the mongoDB compass is changing.
I already read this articles so, please don't mark this question as duplicate.
Refresh/reload the content in Div using jquery/ajax
Refresh Part of Page (div)
refresh div with jquery
reload div after ajax request
I suggest you checking requests between your page and the server in the Network tab of browser's Development Console (F12).
Make sure you see PUT request going out to the server to update todo
Make sure that response you receive looks like { success: true } otherwise the following piece of code won't be triggered
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
Make sure you see GET request going out to the server to pull '#todos' asynchronously.
If you don't see request #3 try the following:
replace location.href with window.location.href
try reloading it manually via console (for Chrome, F12 -> Console tab -> paste $('#todos').load(location.href + ' #todos') and hit Enter). That way you are going to skip first ajax request and just will check whether '#todo' section is loadable/reloadable.
I think it’s a cache problem. Try it like this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: '/todo/${value}?t=202103010001',
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
t=202103010001 Set to a random number

Reload an AJAX loaded page after update

I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.

Ajax link to run codeigniter controller then update html

Sorry for the most simplest of questions but I can't seem to get anything to work. It's the first time I've really played around with AJAX.
I'm developing in codeigniter and I have a link that when clicked runs the controller: photo function: like and allows the logged in user to like the photo then redirects the user back to the photo and displays a slightly different version of the button showing that the user likes the photo.
<?php if ( $like_count > '0' ) { echo $like_count; } ?>
It works fine but I thought it would be cool to replace it with an ajax function so it's more of a fluid motion instead of navigating off the page and then back again.
Any help would be greatly appreciated.
$(".uk-button").click(function(e) {
e.preventDefault();
//Here you can add your ajax
$.ajax({
url: site_url + 'photo/like',
data: {
liked : 1
},
type: 'POST',
dataType: 'json',
async : false,
success: function(success_record) {
console.log(success_record,":success_record");
//You might receive your like count from PHP here
}
});
});
In your success record you would get your PHP record values. Based on that you can increment or decrement count in success function
You can do something like this:
$(document).ready(function()
{
$('.likeLink').on('click', funciton()
{
var obj = $(this);
var id = obj.attr('id'); //anything you want to pass to update your like somewhere
$.ajax(
{
type: 'POST',
url: 'YourFilePathWhereYouWillDoTheLike',
data:
{
id: id,
},
cache: false,
success: function(response)
{
obj.html("You have liked this!");
}
});
return false;
})
})

jquery and ajax request

I have js function which sends ajax request to the controller and succ. return result and append that result into desired div inside partial page. Now I want to implement pagination and I'm using $("#dataList").on("click", ".pagedList a".getPage); to listen when user click on pagination links to determine which page number is clicked
var getPage = function () {
var $a = $(this);
GetTabData(a);
return false;
}
and finally I'm sending pagenumber to the next function which sends pagenumber together with activeTab variable to the controller
function GetTabData(xdata, pageNumber) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: JSON.stringify({ activeTab: xdata, page: pageNumber }),
success: function (result) {
$("[id^='tab-'] div").remove();
var currentTab = $("#tab-" + xdata).html(result);
},
error: function () { alert("error"); }
});
}
Something is definit. wrong here cause on controller side I'm using
Request.IsAjaxRequest()
to allow only ajax request to paginate data and I'm getting Not ajax request. Once more, If I remove pagination option completly and send just activeTab everything works.
Any thoughts?
Your GetTabData function takes 2 arguments: xdata and pageNumber but when calling it you are passing only one:
var $a = $(this);
GetTabData(a);
So you probably are getting a javascript error and the return false statement is never reached.

CakePHP & JQuery, location.reload sometimes not working

Hi I am developing data deleting page with checkbox and button. After deletion, I'd like to display the message either the transaction is successful or not. Most of the time the message shows correctly, but sometimes the page reload doesn't happen and the message won't show until manually reloaded.
Now if it's not certain if the page is reloaded, is there any other way to show the message from the controller?
Here's the code:
(index.ctp)
<script type="text/javascript">
$(document).ready( function() {
$("#btn").click(function() {
var ids = '';
$('input[type="checkbox"]').each(function(){
if(this.checked){
ids = ids.concat(this.id).concat(',');
}else{
jAlert("Please choose items to delete");
}
});
if (ids != ''){
jConfirm('Delete?', 'Confirm',function(r){
if(r==true){
ht = $.ajax({
url: 'items/delete/'.concat(ids),
type: "POST",
contentType: "application/json; charset=utf-8",
});
location.reload(true);
}
});
}
});
});
</script>
(controller.php#function delete())
$this->Session->setFlash(__('Deleted!, true));
$this->redirect(array('action'=>'index'));
CakePHP's session flash is usually pretty reliable.
Perhaps your browser is not reliably doing a hard refresh with location.reload(true). Try window.location = window.location.href + "?nocache=" + new Date().getTime() to manually clear the cache and see if that helps at all.

Categories

Resources