AutoSave Architecture with JQuery AJAX - javascript

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();

Related

AJAX periodical polling data after submit button is clicked

this question might duplicate but I need some help to fix the code.
Scenario: Once the submit button is clicked, ajax will send the form data to server . And based on the form data (variables and update-speed), perform polling to get the response data.
Current bottleneck: Since the speed and variables is declared globally, the correct response will show only first time the submit is clicked and completed. Otherwise for the setTimeout polling for doPoll, it will show null value since the form data is not captured.
Desired Outcome: Once user submit the click button, pull the data periodically based on user'update speed value and save all the response in key-value array. The response will used to draw Chart.js.
Any suggestion and thanks.
Code:
$('#submit-button').click(function(e){
var speed = $('#update-speed-input').val();
var variables = $('#variables-select-input').val();
function doPoll(speed,variables){
$.post("{{ route('getFilterUnitData') }}", {
speed: speed,
variables: variables,
}, function(response) {
console.log(response);
setTimeout(doPoll,speed);
});
}
$.ajax({
url: "{{ route('getFilterUnitData') }}",
method: 'post',
data: {
speed: speed,
variables: variables
}
,
success: function(response){
console.log(count(response));
},
error: function(result) {
console.log(result);
},
complete: setTimeout(doPoll(speed,variables), speed)
});
});
Did you try assigning the values to "window" object? like to window.speed and window.variables
The speed and variables is inside a function scope and not global.

How to display progress from an Ajax call using a custom PHP function?

I have an Ajax call that is processing some data and the length of time it takes varies widely depending on the site. I'd like to set a progress value in the PHP function doing the processing (I'm assuming to a SESSION variable).
While that is processing, I'd like to have another loop that is running and fetching the SESSION variable value every second or so and updating the user on what % is complete as it goes along.
So my main Ajax call to process the data is working and takes place when the user clicks a button. This is in WordPress, so the call looks something like this -
function get_data(refresh){
$.post({
url: ajaxurl,
beforeSend:function(){
$("#loader-gif").show();
},
complete:function(){
$("#loader-gif").hide();
},
data: { refresh: refresh, action: "refresh_data"},
success:function(data){
$("#loader-gif").hide();
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.responseText);
$("#loader-gif").hide();
}
});
}
What do I need to add to this in order to loop as this is running and update a span/div on the page from a PHP session variable?
This is the only Ajax call on the page currently and will likely remain so.
Checkout this link for an progress bar:
https://www.sitepoint.com/community/t/progress-indicator-for-an-ajax-request/100083

More efficient way to refresh div with ajax data

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

how to stop ajax call and start a new one with new parameters?

I've made an ajax call with a jQuery.everyTime() function.
I got a combo box where i select some graph names and dynamically calls to an ajax function, returns a json and creates the chart in the View every 10 seconds.
Everything goes fine but when i select another graph name and click in the function, i don't only have the new graph but i got the old one as well (as a request), so every time i click in a new one (let's say 8 names) i would get 8 requests simultaneously and ofc the latest will be shown (but if you check in firebug you will see the 8 requests).
This is my ajax function:
var selected = $("#name_list :selected").val();
$(".title_graph").text(selected);
var j = jQuery.noConflict();
j("#hour").everyTime(10000,function(i){
j.ajax({
type: "GET",
url: "getchartdata?graphName=" + selected +"&subgroup=hour",
cache: false,
success: function(jsonData){
var data = eval(jsonData);
drawChart(data, data[0][0], data[0][1]);
}
})
});
I would like to cancel previus ajax calls without having to refresh the page. Am i able to do that? like put some kind of "stop" at the very beginning of the function, don't really know. I've seen ajaxName.abort() solution, but i believe it couldn't be applied to what i need.
Thanks in advance.
ADDED:
This is how it looks now with Travis' suggestion:
function getChartsByGraphName() {
var selected = $("#name_list :selected").val();
var ajaxCallHour;
$(".title_graph").text(selected);
var j = jQuery.noConflict();
j("#hour").everyTime(10000,function(i){
ajaxCallHour && ajaxCallHour.abort();
ajaxCallHour = j.ajax({
type: "GET",
url: "getchartdata?graphName=" + selected +"&subgroup=hour",
cache: false,
success: function(jsonData){
var data = eval(jsonData);
drawChart(data, data[0][0], data[0][1]);
}
})
});
}
But it's still sending old ajax requests.
See this answer: Abort Ajax requests using jQuery
Create a variable outside of your everyTime that stores the xhr, then stop it before issuing a new one.
var xhr;
j("#hour").everyTime(10000,function(i){
xhr && xhr.abort();
xhr = j.ajax();
});

AJAX read data in a progressive manner not just when it's completed

I like to create a progress bar for my ajax calls.
For this I can make my server side script to return the state of it's progress.
So I need for javascript to read this progress level and show it.
Is it possible or am I on the wrong road?
You could try something like this (some pseudocode, assuming jQuery, since you've tagged the question as such):
var poll;
$.ajax({
url: 'your_ajax_script',
beforeSend: function(){ // set up out-of-band status polling
poll = setInterval( function(){
$.get('your_script_that_returns_status',
function(data){
update_progressbar(data);
});
}, 1000 ); // update every second?
},
success: function(data) {
clearInterval( poll ); // stop polling
finalize_or_hide_progressbar(); // clean up
do_something_with( data ); // your "done" logic
}
});
Either poll at intervals, returning the payload on the final successful call, or run two AJAX calls - the first retrieving the actual data, and the second polling for update percentage.

Categories