abort long polling ajax request and restart request with new parameter - javascript

how do I cancel an ajax request, then call it again with new parameter? with my code, the previous ajax requests still hang around.
var stats_url = '/stats';
var live_stats_ajax_object = $.ajax();
$(".check-round").on("click", function(){
live_stats_ajax_object.abort();
round = $(this).attr('class').split(' ')[0];
get_live_stats(round);
});
var get_live_stats = function(round) {
live_stats_ajax_object = $.ajax({
url: stats_url,
type: "GET",
data: 'live_stats=true' + "&event_id=" + $( "#event-list option:selected" ).val()
+ "&fight_id=" + $( 'input[name=fightlist]:checked' ).val()
+ "&round=" + round,
dataType: "json",
timeout: 3500,
complete: function(xhr, textStatus) {
console.log("polling again stats for " + round);
if (textStatus != "abort") {
setTimeout( function() { get_live_stats(round); }, 10000 );
}
},
success: function(data) {
console.log("polling and got live stats for " + round);
console.log(data);
}
})
.fail(function() {
console.log("polling failed and couldn't get live stats for " + round);
})
};
I have been on this for hours. Thanks

Edit, Updated
Try
// create empty object
var live_stats_ajax_object = {}
// reference for `setTimeout` within `get_live_stats`
, id = null
, stats_url = "/stats"
, get_live_stats = function (round) {
var eventlist = $( "#event-list option:selected" ).val()
, fightlist = $( 'input[name=fightlist]:checked' ).val();
live_stats_ajax_object = $.ajax({
type: "GET",
url: stats_url,
data: "live_stats=true&event_id="
+ eventlist
+ "&fight_id="
+ fightlist
+ "&round="
+ round,
timeout: 3500
});
// return `live_stats_ajax_object`
return live_stats_ajax_object
.done(function (data, textStatus, jqxhr) {
console.log("polling and got live stats for " + round + "\n"
, data);
})
.fail(function (jqxhr, textStatus, errorThrown) {
console.log("polling failed and couldn't get live stats for "
+ round);
})
.always(function (jqxhr, textStatus) {
if (textStatus !== "abort") {
// set `id` to `setTimeout`'s `numerical ID`
// call `get_live_stats()` within `setTimeout`
id = setTimeout(function () {
get_live_stats(round);
}, 10000);
}
});
};
$(".check-round").on("click", function () {
var round = $(this).attr('class').split(" ")[0];
// at initial click `live_stats_ajax_object` is empty object ,
// not having `jqxhr` `promise` property ;
// call `get_live_stats()` , which sets `live_stats_ajax_object`
// to `$.ajax()` , having `state` property at returned `jqxhr` object
if (!live_stats_ajax_object.hasOwnProperty("state")) {
get_live_stats(round);
} else {
// if `id` was set during initial call to `get_live_stats()`
if (id) {
// `.abort()` previous `live_stats_ajax_object` request ,
// `clearTimeout()` of `id` , set `id` to `null`
// call `get_live_stats()` with current `round` argument
live_stats_ajax_object.abort();
clearTimeout(id);
id = null;
get_live_stats(round);
}
}
});
jsfiddle http://jsfiddle.net/guest271314/7wrdo5wr/

Related

Getting resolved data undefined in jquery

I am trying to call synchronous call for getting data count using ajax call.
Here is my Jquery Code:
var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();
function tilesCount(tilename, count)
{
var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
count = 0;
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
$(data.value).each(function (i, folder) {
count = count + 1;
});
console.log("Call 1: " + count)
ItemCount.resolve(count);
return count;
},
error: function(error){
console.log("Error: " + JSON.stringify(error));
ItemCount.reject;
}
});
}
$(document).ready(function () {
var count = tilesCount("");
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
Output:
Call 1: 1
Call 2: undefined
Synchronous call working perfectly, but I am getting data as undefined
Since ajax is asynchronous return count; will be empty
var count = tilesCount("");
So the best solution is to just passed a callback function inside your method which can be call whenever your ajax is completed
function tilesCount(tilename, count, callback)
Wrap this inside your callback function
function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
}
so your $(document).ready will be like this and just add parameter count inside the callback
$(document).ready(function () {
tilesCount("", "", function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
});
your javascript code would be like this now
var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();
function tilesCount(tilename, count, callback)
{
var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
count = 0;
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
$(data.value).each(function (i, folder) {
count = count + 1;
});
console.log("Call 1: " + count)
ItemCount.resolve(count);
return callback(count);
},
error: function(error){
console.log("Error: " + JSON.stringify(error));
ItemCount.reject;
}
});
}
$(document).ready(function () {
tilesCount("", "", function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
});

Disable page behind on processing using Javascript in MVC4

I am using MVC4 in my project. On click of a button on a page, I need to show a dialog and then on confirmation, I need to do an event processing.
$('#btn1).click(function (e) {
e.preventDefault();
var meetingvar = new Array();
var cells = $(this).closest('td').siblings('td');
meetingvar = $(cells[2]).text().split(",");
var params = {};
params.meetingdate = meetingvar[0];
params.meetingstate = meetingvar[1];
params.meetingvenue = meetingvar[2];
$.ajax(
{
type: 'GET',
url: '/[Controler]/[action1],
data: { MeetingDate: params.meetingdate, MeetingState: params.meetingstate, MeetingVenue: params.meetingvenue },
beforeSend: function (jqXHR, settings) {
setLoaderLabel('Please wait...');
showLoader();
}
}).done(function (data, textStatus, jqXHR) //success callback
{
if ($.trim(data) == 1) {
var dialog = $('<p>Confirmation Required. Do you want to overwite ?</p>').dialog({
buttons: {
"Yes": function () { //alert('you chose yes');
window.location.href = '/[Controller]/[Action2]?MeetingDate=' + meetingvar[0] + '&MeetingState=' + meetingvar[1] + '&MeetingVenue=' + meetingvar[2] + '&toGen=1';
},
"No": function () { //alert('you chose no');
window.location.href = '/[controller]/[action2]?MeetingDate=' + meetingvar[0] + '&MeetingState=' + meetingvar[1] + '&MeetingVenue=' + meetingvar[2] + '&toGen=0';
},
"Cancel": function () {
dialog.dialog('close');
}
}
});
}
if ($.trim(data) == 0) {
showLoader();
window.location.href = '/[controller]/[action1]?MeetingDate=' + meetingvar[0] + '&MeetingState=' + meetingvar[1] + '&MeetingVenue=' + meetingvar[2] + '&toGen=1';
}
if ($.trim(data) == 2) {
ShowErrorMessage('<p>NOT DEFINED</p>');
}
}).fail(function (jqXHR, textStatus, errorThrown) //error callback
{
var errorMsg = GetAjaxResponseTitle(jqXHR.responseText);
ShowErrorMessage('<p>' + errorThrown + '</p>' + errorMsg);
hideLoader();
}).always(function () //complete callback
{
hideLoader();
});
});
Here , on success, from first action1 is it going to success, with the Loader(basically disabling the main page). But I need the same Loader functionality on Click of Yes or No, because, before redirecting there is an event which takes some time. At this stage, shouldn't allow user to click on any other button on the base page. Don't know how to achieve this. Please appreciate any help.
Thanks In advance

JSON Data log and sent to server

I have a javascript function which generates JSON data at every certain second and then PUT it to a cloud server. Now I don't want to POST in realtime, rather I want to log this data in a buffer and say after n number of data log I will PUT to cloud. For example I want to log 50 data point in 10 second and then with timestamp I will PUT to a server
Now JSON data is passed through var fromDatan. JSON data format is
{"value":"-2.1282838391939194"}
Now the code is:
var acc;
var watchID = null;
function startWatch() {
//set frequency of accelerometer update.1000 = 1 second
var options = { frequency: 1000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
//DISPLAY ACCELERATION DATA
function onSuccess(acceleration) {
acc = acceleration;
var element = document.getElementById("accelerometer");
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
datalock();
}
function postdata () {
var accx = acc.x;
alert(accx);
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
//POST JSON DATA
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9asdedqedqxdqd7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
}
function datalock(){
alert("Entering");
fromData.push({
value: accx.toString(),
});
if (fromData.length >= 10) {
postdata ();
};
var fromData;
}
It is not working, although all other things are correct, the pushing I couldn't implement properly. Can anyone please help me out?
EDIT START
Try this:
var fromData = [];
var jsonCounter = 0;
function postdata () {
var accx = acc.x;
alert(accx);
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9asdedqedqxdqd7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
}
function datalock(){
alert("Entering");
fromData.push({
value: accx.toString(),
});
jsonCounter++;
// post only after 10 entries
if (jsonCounter >= 10) {
postdata ();
jsonCounter = 0; // reset
};
}
EDIT END
Since JSON object does not have a length property, you can do it by using a variable.
Example:
var formdata;
var jsonCounter = 0;
function datalock(){
alert("Entering");
fromData.push({
value: accx.toString(),
});
jsonCounter++;
// post only after 50 entries
if (jsonCounter >= 50) {
postdata ();
jsonCounter = 0; // reset
};
//var fromData; // make it global as it is used in other function.
}
This is my code so far after modifying it as per suggestion from #web-nomad
function postdata () {
var accx = acc.x;
alert(accx);
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
//POST JSON SENSOR DATA
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9e259asdasd6a7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
//var fromData = {};
}
var fromData = [];
var jsonCounter = 0;
//Edit start
function datalock() {
alert("Entering");
//alert(jsonCounter); //It was showing me only count as 0
fromData.push({
value: accx.toString(),
});
alert(JSON.stringify(fromData));// no alert
jsonCounter++;
alert(jsonCounter); //The alert was not coming at all, when I tried this one
// post only after 10 entries
if (jsonCounter >= 10) {
postdata ();
jsonCounter = 0; // reset
};
}
//Edit End
This is the change after your suggestion given #web-nomad

javascript formatting

I have a piece of code that seems to have a problem. I've tried JSLint and other tools to see where I might have a missing delimiter. Eclipse doesn't show me anything either. In Firebug, the complete block of code shows as disabled line numbers like comment lines do. Anyone know of a good tool? I used ctrl+K to indent the code I pasted below.
$(document).ready(function() {
$('.startover').live('click', function() {
var ReInitAnswer = confirm('Are you sure you want TO start over FROM SCRATCH?');
if (ReInitAnswer){
return true;
}
ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function(e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({ type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown){
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function(l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function(i){
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter){
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger ('click');
});
$(".alphabet").hover(function () {
var _$this = $(this);
var usercount = 0;
$.ajax({ type: "POST",
url: "scribble.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + $(this.target).val(),
datatype: "html",
success: function(res){
usercount = eval("(" + res + ")").DATA[0][0];
_$this.append($("<span> (" + usercount +")</span>"));
},
error: function (xhr, textStatus, errorThrown){
console.log('errorThrown');
}
});
},
function () {
$(this).find("span:last").remove();
}
);
});
It's really difficult to tell what you're asking, but if you mean it's formatted wrong, try http://jsbeautifier.org/ for better formatting. Here's that code cleaned up (including the incorrect casing of else):
$(document).ready(function () {
$('.startover').live('click', function() {
var ReInitAnswer = confirm('Are you sure you want TO start over FROM SCRATCH?');
if(ReInitAnswer) {
return true;
} else {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function(e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function(l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if(CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
$(".alphabet").hover(function() {
var _$this = $(this);
var usercount = 0;
$.ajax({
type: "POST",
url: "scribble.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + $(this.target).val(),
datatype: "html",
success: function(res) {
usercount = eval("(" + res + ")").DATA[0][0];
_$this.append($("<span> (" + usercount + ")</span>"));
},
error: function(xhr, textStatus, errorThrown) {
console.log('errorThrown');
}
});
}, function() {
$(this).find("span:last").remove();
});
});
Javascript is case sensitive.
ELSE must be lowercase.
ELSE must be lowercase
ELSE { // <-- this is bad
alert('canceled');
return false;
}

What makes the entire script block disabled?

When I check this code in Firebug, the entire block is disabled.
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
</script>
You have to replace all uppercase ELSE with else (JavaScript is case-sensitive).
Add the closing brace and parenthesis at the end of the code, to finish the $(document).ready(function(){ block.
Working code:
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} else { // <------------------------------------ ELSE > else
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else { // <------------------------------------ ELSE > else
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
}); // <---------------------------------------------------- Added });
</script>

Categories