I am working on new app in javascript. What I need is that whenever latest news is added to the database at the backend then the front end should know about it and update that area asynchrnously. What is the best and efficient way to achieve this in JavaScript and/or jQuery?
I would recommend using long polling. With a quick Google search you should be able to get up and running. For example here.
use Window.setInterval() to reload the page for specific interval of time so that the news gets updated
$.ajax Documentation
make a function get_news which contains ajax request which well get updated content from the server.
setInterval(get_news, 1000) will call the function get_news after every 1000 ms
function get_news() {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$('#content').html(data);
}
dataType: dataType
});
}
setInterval(get_news, 1000); //1000 ms
Related
I have a method which checks for notifications and executes a js.erb in return.
The JS which is triggering this method is given below:
setInterval(function () {
$.ajax({
url: "http://localhost:3000/checkNotification",
type: "GET"
});
}, 15000);
This is working great but I am worried about the performance of the site once it will be in production.
Will this cause a performance issue?
If yes, is there another way to solve this problem?
one suggestion I would make is to take advantage of the callback function of ajax so that if a request takes longer than expected it will not fire again until the last one completes
function checkNotifications(){
$.ajax({
url: "http://localhost:3000/checkNotification",
type: "GET",
success: function(){
setTimout(checkNotification, 15000);
}
});
};
also if for some reason the server were to respond with a 500 error, it would prevent the function from continuing
I have built an ajax chat app, but now when it refreshes the chats (loading all the new chats) it seems to pause between removing all the current chats and loading all the chats including the new one. This is set on a timer, so whenever it runs, it sort of has this gap of blankness and then jumps to the top of the page (the top of the div getting refreshed) What do I need to do to ensure that this doesn't happen? ie: how do I take the waiting period out / do it different?
$(document).ready(function() {
window.setInterval(function(){
$('#chat-messages').empty();
getMessages(meid, friendid);
}, 5000);
});
$.ajax({
url: 'getAllMessages.php',
data: 'id='+id+'&&friend='+friendid,
type: 'POST',
success: function(res) {
// processing code goes in here, it was too long so I took it out.
}
});
$.ajax({
url: 'getAllMessages.php',
data: 'id='+id+'&&friend='+friendid,
type: 'POST',
success: function(res) {
$('#chat-messages').empty();
// empty on success to avoid delay caused due to ajax request
}
});
Decrease Interval time
Add new content instead of removing old content and adding new content.
Use setTimeout call and add it to success block
I think the best thing you can do is add a new parameter named "last-update" and get only the new messages from the last success query...
Than, you just need to do something like
$('#chat-messages').append(new_messages)
You will optimize chat refresh, network latency and mysql :-)
I'm making a dynamic webpage which retrieves lots of data from a database very frequently, like at least every 3 seconds.
I tested my webpage and database locally by using XAMPP. It works perfectly. However, it turns to be very slow after I upload everything to 000webhost (my free account). My webpage even freezes (I cannot scroll the page, not even doing anything but wait for the data to be transferred.) when retrieving the data.
I used a setTimeout function which called several ajax commands to read data from my database. I have optimised the data capacity already, but the page still freezes. I also tried to disable most of the ajax commands and only left one. When loading, the page freezes just as a blink, but anyhow it still freezes...
Most of my ajax commands are like below which simply retrieves data from my database and updates the related fields on my webpage. Some ajax commands uses $.parseJSON() because I need the whole row from a table.
$.ajax({
type: "GET",
url: "get_balance.php",
data: {wherematch: localStorage.login_user},
dataType: "html", //expect html to be returned
async:false,
success: function(response){
document.getElementById('balance').innerHTML = response;
}
});
Can anyone provide some suggestions how to solve this issue? Should I pay and get a better account?
Thanks.
to have an ajax refreshing every 3 s, your javascript & ajax must be like this:
function get_data(){
$.ajax({
type: "GET",
url: "get_balance.php",
data: {wherematch: localStorage.login_user},
dataType: "html", //expect html to be returned
success: function(response){
document.getElementById('balance').innerHTML = response;
setTimeout(get_data(),3000);
}
});
}
get_data();
Put setTimeout() function inside the ajax. You will not get freeze because we don't set async as false
I'm trying to create a real-time website analytics dashboard which creates an open HTTP connection to the server using jQuery/JavaScript asynchronously to poll the server for updates to the data as and when they occur.
The obvious start for this would be to use an XMLHttpRequest object or jQuery's $.ajax method to send a GET or POST request to the server asynchronously requesting some data.
However, beyond sending one request at a time using a setInterval method every 30 seconds I am not sure how to make the connection to the server persistent. Basically, I only want to send one http request and ensure the connection to the server stays open for polling!
My example code with setInterval is as follows:
<div id="analytics"></div>
<script>
var analytics = document.getElementById('analytics');
setInterval(function(){
$.ajax({ url: "http://server.com/", success: function(data){
analytics.innerHTML = data;
}, dataType: "json"});
}, 30000);
</script>
After searching online, this was the answer I was looking for which doesn't use sockets.io nor WebSockets but does use jQuery by taking advantage of its complete method to create an artificial loop:
<div id="analytics"></div>
<script>
var analytics = document.getElementById('analytics');
(function poll(){
$.ajax({ url: "server", success: function(data){
analytics.innerHTML = data;
}, dataType: "json", complete: poll, timeout: 30000 });
})();
</script>
Source is Tian Davis from Technoctave: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery
I am using ajax to load my website content and want to update the window location when ajax is successful.
How can I update the window location to "/newpage"?? I need users to be able to go back and to refresh. Is this possible??
I'm assuming you're using jquery to make the AJAX call so you can do this pretty easily by putting the redirect in the success like so:
$.ajax({
url: 'ajax_location.html',
success: function(data) {
//this is the redirect
document.location.href='/newpage/';
}
});
You can set the value of document.location.href for this purpose. It points to the current URL. jQuery is not required to do this.
you can use the new push/pop state functions in the history manipulation API.
Assuming you want to change the url to another within the same domain, you can use this:
history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');
If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin
Use document.location.href to change the page location, place it in the function on a successful ajax run.
I'm writing common function for change window
this code can be used parallel in all type of project
function changewindow(url,userdata){
$.ajax({
type: "POST",
url: url,
data: userdata,
dataType: "html",
success: function(html){
$("#bodycontent").html(html);
},
error: function(html){
alert(html);
}
});
}