More efficient way to refresh div with ajax data - javascript

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 :-)

Related

Extend the time of an AJAX request

I have a function on the server to create hundreds of elements and store them in the database. This action takes time on the server and when the action finalize, it returns the result. The problem is that Ajax terminates the request after around 150000ms with Bad Request 400 and the runningProcess response.
The Ajax call is:
showProgressCursor();
$.ajax({
type: "POST",
url: strUrl,
data: {accountId: byId("account-id").value},
dataType: "JSON",
success: function (oResult, strTextStatus, internalResponse) {
console.log("Success")
_showTheResult(oResult, strTextStatus, internalResponse, allDataError);
hideProgressCursor();
},
error: function(oResult) {
manageError(oResult);
console.log(oResult);
hideProgressCursor();
}
});
Do you know how I can increase this time or cancel it until Ajax receives an answer?
Extra: at the moment, I am showing a loading wheel but it would be better if I show a bar with the progress of the operation, could I show something like that? (I have thought of making a different recurring request (every second for example) and obtaining the total created and the total to be created and thus be able to have the progress. I don't know if this is a good solution)

Efficient way of passing data and calling background script in PHP

I have a page where I show 5 questions to a user and when he clicks on Next 5 link I am sending the score of current page onbeforeunload() to the script updateScore() asynchronously using jQuery AJAX and when the call is successful the next 5 questions are displayed.
window.onbeforeunload=function()
{
$.ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
cache: false,
timeout:5000,
async:false
});
}
But the problem is that on slow connections,it might hang the browser for a while until AJAX call returns successfully.When I tried async:true(default) the next page is loaded first without making call to updateScore.php.It might be due to the fact that connection is fast in localhost hence giving no time for the AJAX call to complete.This was the reason I used async:false.Will it happen (making no AJAX call) if I use async:true in practical case as well?If yes, is there a way to come around this problem?
I advice you to change your code a bit.
Make ajax request on "click" event, and redirect user inside ajax callback function.
Like this:
$('#mybutton').on('click', function()
{
$('#pleasewait').show();
$ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
success: function() { document.location="nextpage.php" }
});
}

update news after a regular period of time

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

AutoSave Architecture with JQuery AJAX

I would like to implement the AutoSave functionality for my site.
I mean, I would want all the fields which are edited by the user throughout the site should be autosaved without any button clicks. So user can keep editing.
[site designed with: CodeIgniter and JQuery].
This feature, I am implementing as follows.
1.Created a Queue data structure in javascript and to which I am pushing all the changes made by user. So this is like an object holding all the user changes.
2.Then wrote a function to save the contents of this Queue to the database.
function start(){
var changeData = dq.get(); //getting the data from Queue
while(changeData !== undefined){
$.ajax({
type: 'POST',
url: '/ci/ajax/insert/',
data: {changeData},
success: function(data, status, xml){
alert('succefully inserted data -- '+data);
}
});
changeData = dq.get();
}
setTimeout(function(){ start(); }, 5000);
};
start();
Here I am setting the interval as 5 sec.
The problem is that, I am making two or more changes within 5 sec, but, only the first change is getting updated. But I am getting the alert 2 or more times depending on changes I made.
Where I am going wrong?
Also suggest me the better ways of implementing the autosave feature.
Thanks!
You should define the setTimeout in the success method it would be great because when your first request will be completed then generate the second request otherwise if you will not wait for the server response and sending the no. of requests it be increase the load on your server
function start(){
var changeData = dq.get(); //getting the data from Queue
while(changeData !== undefined){
$.ajax({
type: 'POST',
url: '/ci/ajax/insert/',
data: {changeData},
success: function(data, status, xml){
setTimeout(function(){ start(); }, 5000);// defines when first request is accomplished
alert('succefully inserted data -- '+data);
}
});
changeData = dq.get();
}
};
start();

Could it be, that Chrome cancels pending Ajax requests, once the browser is being redirected to another URL?

I have this function to unlock a list the user is currently editing:
function unsetLock(id) {
$.ajax({
type: "POST",
url: "/ajax.php?action=unsetLock",
dataType: 'json',
data: "id="+ id
});
return true;
}
When the user navigates away from the list, I have to cancel the lock:
unsetLock(lockID);
document.location.href='/page/to/navigate/back/to.php';
However this unlock sometimes works and sometimes doesn't. I think it is because document.location.href is executed, before the ajax call has actually been sent to the server.
How can I force to send the unlock before navigating the user to the next page?
Actually I don't need to wait for the Ajax-Reply, since I want to redirect the user, whether it succeeds, or not. I just want to make sure, it is being transferred to the server.
If I place the document.location.href inside the Ajax function, it will wait for the reply.
A really bad-mannered way to do it is to add: async: false, which will lock the browser up until the AJAX call is complete.
Of course, if there is a problem and the AJAX call never completes...
It's the quickest and easiest solution to your problem, but probably not the best.
I, personally, would have the lock only last for twenty seconds (using a timestamp in the database), and send an ajax call every ten seconds to re-lock the page (if that makes sense) using setInterval().
That way the lock will unset itself a few seconds after someone leaves the page, and is good no matter what the situation (a power failure for the client wouldn't leave the page locked forever, for example).
Perhaps I'm missing something, but why not use the success option in the Ajax call? This will execute whatever the outcome and makes sure it reaches the server.
function unsetLock(id) {
$.ajax({
type: "POST",
url: "/ajax.php?action=unsetLock",
dataType: 'json',
data: "id="+ id,
success: function(){
document.location.href='/page/to/navigate/back/to.php';
}
});
return true;
}

Categories