This code is supposed to request new chat messages and append them to the content on my website. The problem, though, is that it sometimes freezes and stops requesting new messages.
(function worker() {
$.ajax({
url: '/client_message.php?get_message=yes&chat_id=<?php echo $chat_id; ?>&user_id=<?php echo $uid; ?>',
success: function(data) {
content = data;
if(content != "" && content != prev) {
$("#chat_wrapper").append(content);
prev = content;
$("html, body").animate({ scrollTop: $(document).height() }, "slow");
titleStuff();
}
},
complete: function() {
setTimeout(worker, 700);
}
});
})();
Please let me know if you need more information to figure out what could be wrong.
Adding this code did the trick:
$.ajaxSetup({ cache: false });
Seems like the problem was a result of the jQuery cache.
Related
I am using ajax to load data when user scroll further down the page . i am using async = false; which will stop the calls to the ajax function unless the already running call is completed. Yes , its not recommended to use async. but to prevent data disorder i have to use it.
Here is my ajax function
<script type="text/javascript">
var page = 1;
var busy = false;
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop)
{
if( $(window).scrollTop() + $(window).height() > $(document).height()-550 && busy == false)
{
loadMoreData(page);
page++;
}
}
lastScrollTop = st;
});
function loadMoreData(page){
$.ajax(
{
type: "POST",
url: '<?php echo base_url('sura/load_verse/'.$sura_id.'/')?>'+page,
async: false,
cache: false,
beforeSend: function()
{
$('#loader_message').show();
}
})
.done(function(data)
{
if(data == ""){
$('.ajax-load').html("No More Data Found");
return;
}
$('.ajax-load').hide();
$("#post-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
});
busy = false;
$('#loader_message').hide();
}
</script>
but the async call does not let the browser to show my loading image $('#loader_message').show(); while the call is fetching the data.
can somebody help me in showing the image while using the async call .Or is there an alternative for async which will stop multiple request at the same time.
Thanks
I believe the solution is to show the loader before starting the ajax call. beforeSend doesn't work because the DOM is not modified until after $.ajax() is done and showing the loader qualifies as modifying the DOM.
Below is my suggested solution. I changed your code a bit to use what I feel are "best practices" for javascript. One thing I always avoid is using PHP code inside the javascript. What you do with base_url() will become a problem if you move your javascript to an external file. That is why I usually define a var baseURL as shown below.
I also cache any JQuery object that needs to be created more than once which is why the vars thisWindow and loader were added.
It also appears that once you set busy = true it is never changed back to false. That is remedied by adding an .always call which runs busy=false. The loader is also hidden in .always so that you can be certain it will removed even if there is an ajax .fail.
I think that with busy being properly managed you can use async: true,. I strongly recommend you give that a try.
Here's my answer
<script>
var page = 1;
var busy = false;
var baseURL = window.location.protocol + "//" + window.location.hostname;
var lastScrollTop = 0;
var thisWindow = $(window);
var loader = $('.ajax-load');
thisWindow.scroll(function (event) {
var st = $(this).scrollTop();
if (st > lastScrollTop)
{
//check busy first, if busy=true you avoid making calls
//do scrollTop() and height()
if (busy == false && thisWindow.scrollTop() + thisWindow.height() > $(document).height() - 550)
{
loadMoreData(page);
page++;
}
}
lastScrollTop = st;
});
function loadMoreData(page) {
busy = true;
loader.show();
$.ajax(
{
type: "POST",
url: baseURL + "/sura/load_verse/$sura_id/" + page,
async: false,
cache: false,
})
.done(function (data)
{
if (data == "") {
loader.html("No More Data Found");
return;
}
$("#post-data").append(data);
})
.fail(function (jqXHR, ajaxOptions, thrownError)
{
})
.always(function () {
busy = false;
loader.hide();
});
}
</script>
Please see my code below. I want to auto refresh a div on a php page. I tried to refresh through javascript and html header, but it is slowly slowing down my computer.
page2.php
<?php
if($_GET['type']!='ajax'){
include 'header.php';
echo "<div id='main-content'>";
}
?>
Itm 1</br>
Itm 2
<img class="ajax-loader" src="ajax-loader.gif" alt="loading..." />
<?php
if($_GET['type']!='ajax'){
echo "</div>";
include 'footer.php';
}?>
app.js
$.cergis = $.cergis || {};
$.cergis.loadContent = function () {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
if (pageUrl != window.location) {
window.history.pushState({ path: pageUrl }, '', pageUrl);
}
}
$.cergis.backForwardButtons = function () {
$(window).on('popstate', function () {
$.ajax({
url: location.pathname + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
}
});
});
}
$("a").on('click', function (e) {
pageUrl = $(this).attr('href');
$.cergis.loadContent();
e.preventDefault();
});
$.cergis.backForwardButtons();
i have tried different variation but no luck. please help me.
thanks.
app.js changed...
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
}
setInterval(function(){myTimer()}, 1000);
Try setTimeout:
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
setTimeout(myTimer,1000);//so that the request ends setTimeout calls a new request.
},
error: function () {
setTimeout(myTimer,1000);//If there is an error in the request the "autoupdate" can continue.
}
});
}
myTimer();//fire
this way setTimeout() waiting to finish the request to invoke a new request.
setInterval() does not wait, which makes simuntaneos generate multiple events, which causes the slowness.
You can use setTimeout($.cergis.loadContent, 1000); to refresh once or setInterval($.cergis.loadContent, 1000); to refresh each seconds (1000 milliseconds = 1second).
See http://www.w3schools.com/js/js_timing.asp
I'm programming a site, and I've got a problem.
I have the following jQuery code:
$('input[type="text"][name="appLink"]').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
Sometimes (randomly) the content fades out-in twice.
Could you let me know what's wrong?
Thanks in advance.
I guess the page is dynamically generated from javascript,
If you execute the following function twice, then there be two events since it executes twice,
so a better way is to unbind all previus 'keyup' event and bind it again.
Try this,
$('input[type="text"][name="appLink"]').unbind('keyup').keyup(function() {
});
Hi im currently developing this site:
http://remedia-solutions.com/clientes/0039_kiplingmexico/demo2/
its almost done but im currently having some troubling on a section "Coleccion" in this section the first thing you do is select a specific type of bags , once you select it, you will get only 20 bags loaded (this bags are loaded from a mysql db) when you get to the bottom of the page it will show another 20 bags. Now the problem here is that when i get to the bottom the JS function runs like 5 times :/ So is there a way it only run once then wait a bit and run it again?
Heres my Jquery code
Once you click a "Coleccion" it will do this:
$("#coleccionmenu span").click(function() {
$("#coleccionmenu span").removeClass('focuscoleccion')
$(this).addClass('focuscoleccion');
$("#contbolsas").fadeOut('fast')
var id = this.id;
$.ajax({
url: "respuestabolsas.php",
type: "POST",
data: "id=" + id,
complete: function() {
//called when complete
},
success: function(x) {
$("#contbolsas").css("display", "none");
$("#contbolsas").html(x)
$(".bolsacargada").css('opacity', '0');
$("#contbolsas").css("display", "block");
$(".bolsacargada").each(function(index) {
$(this).delay(300*index).animate({opacity: 1}, 400);
});
hovercolores();
if ($('#contbolsas > div:contains("Rawr")').length > 0) {
$("#text").fadeOut()
return false;
}
else{
$("#text").fadeIn()
cargamascoleccion(id)
}
},
error: function() {
//called when there is an error
},
});
});
Once is loaded i need the id from the collection you just clicked so when you scroll down it only show those collections and not the other ones:
function cargamascoleccion(id){
$("#todocoleccion").scroll(function() {
var bottom = $("#todocoleccion").scrollTop() - $(window).height();
if( bottom > $(".bolsacargada:last").offset().top + 300 ){
$.ajax({
url: "respuestabolsas2.php",
type: "POST",
data: "id=" + id + "&idultimabolsa=" + $(".bolsacargada:last").attr('id'),
complete: function() {
//called when complete
},
success: function(x) {
hovercolores();
if(x != ""){
$("#contbolsas").append(x)
}
else{
$("#text").fadeOut()
return false;
}
},
error: function() {
//called when there is an error
},
});
}
});
}
I doubt theres a problem on the php code i think the problem is on the function above cause it runs like 4 times when i get to the offset of the last bag. Any ideas?
It looks like its firing the ajax call multiple times because the condition is met multiple times while the user is scrolling. You might want to add another condition to the if statement before executing the ajax call which checks whether it has already been initiated. Something along the lines of
var ajaxComplete = true;
$("#todocoleccion").scroll(function() {
var bottom = $("#todocoleccion").scrollTop() - $(window).height();
if (bottom > $(".bolsacargada:last").offset().top + 300 && ajaxComplete) {
$.ajax({
url: "respuestabolsas2.php",
type: "POST",
data: "id=" + id + "&idultimabolsa=" + $(".bolsacargada:last").attr('id'),
beforeSend: function() {
ajaxComplete = false
},
complete: function() {
//called when complete
ajaxComplete = true;
},
success: function(x) {
hovercolores();
if (x != "") {
$("#contbolsas").append(x)
}
else {
$("#text").fadeOut()
return false;
}
},
error: function() {
//called when there is an error
},
});
}
});
Is there anyway that I can make it so the page will automatically scroll to the top after the content has loaded (via Ajax)?
This is the code I have for displaying the content:
$(document).ready(function () {
var my_layout = $('#container').layout();
$("a.item_link").click(function () {
$("#loader").fadeIn();
feed_url = $(this).attr("href");
$.ajax({
type: "POST",
data: "URL=" + feed_url,
url: "view.php",
success: function (msg) {
$("#view-area").html(msg);
$("#loader").fadeOut();
}
});
return false;
});
});
So after the 'view-area' has loaded its content can I make the page auto scroll to the top?
Just use the scroll function
scrollTo(0);
If you want the jquery, then here is a good example with smoothing :)
From the link:
$('html, body').animate({ scrollTop: 0 }, 0);
//nice and slow :)
$('html, body').animate({ scrollTop: 0 }, 'slow');
To put it in your code
...
success: function (msg) {
$("#view-area").html(msg);
$("#loader").fadeOut();
//Put code here like so
$('html, body').animate({ scrollTop: 0 }, 0);
}
You can do $(window).scrollTop(0);
All ajax requests have a callback argument so use scrollTop(0).
Check the jQuery documentation on how to use ajax callbacks.
If you have no callback, try to bind an event listener:
document.addEventListener(
"load",
function(event) {
event.composedPath().forEach(function(dom) {
if (dom.classList && dom.classList.value === "classOfLoadedContent") {
$(".div-to-be-scrolled").scrollTop($(".content").innerHeight());
}
});
},
true
);