I have an ajax call using jquery.
$.ajax({
type: "POST",
url: "recorded-vigil.aspx/GetCameraTimeLineMinutes",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
error: function (xhr) {
$('.loader').hide();
alert('Error in fetching timeline. Please try again');
console.log(xhr);
},
success: function (results) {
$('.loader').hide();
$('#spnTimeSelect').html("Please select minute");
console.log('GetCameraTimeLineMinutes');
if (results != null && results.d != null && results.d.result != null) {
var HourSel = $("#MinuteSelect").empty();
for (var i = 0; i < results.d.result.length; i++) {
var Minute = i;
//if (results.d.result[i] == 1)
// HourSel.append('<button class="dayClass activeCam minuteClass" data-minuteindex="' + Minute + '">' + Minute + '</button>');
//else
// HourSel.append('<button class="dayClass minuteClass" data-minuteindex="' + Minute + '">' + Minute + '</button>');
if (results.d.result[i] == 1)
HourSel.append('<div class="btn on minbutton minuteClass" data-minuteindex="' + Minute + '">' + Minute + '</div>');
else
HourSel.append('<div class="btn minbutton minuteClass" data-minuteindex="' + Minute + '">' + Minute + '</div>');
//if (i == 16)
// oSel.append('<hr style="visibility:hidden;"><div id="dayBreak"> </div>');
}
breakMinutes();
$('.minuteClass').on('click', onMinuteClick);
}
}
});
This used to throw error because of server timeout.
Is there any way to fire this again on error. If we try this say 3 times, then we can show the timeout error. Is it possible?
If I understand your situation correctly, then yes this is possible. There are many ways you can achieve this - consider the following adjustments to your code to show how this could be achieved:
var retries = 3; // Track the number of retries
function doRequest() {
$.ajax({
type: "POST",
url: "recorded-vigil.aspx/GetCameraTimeLineMinutes",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
error: function (xhr) {
$('.loader').hide();
alert('Error in fetching timeline. Please try again');
console.log(xhr);
retries--; // Decrement the number of remaining retries
if(retries >= 0) { // If more retries available, fire another request
doRequest()
}
},
success: function (results) {
retries = 3; // Optional reset if you want to do this also
$('.loader').hide();
$('#spnTimeSelect').html("Please select minute");
console.log('GetCameraTimeLineMinutes');
if (results != null && results.d != null && results.d.result != null) {
var HourSel = $("#MinuteSelect").empty();
for (var i = 0; i < results.d.result.length; i++) {
var Minute = i;
//if (results.d.result[i] == 1)
// HourSel.append('<button class="dayClass activeCam minuteClass" data-minuteindex="' + Minute + '">' + Minute + '</button>');
//else
// HourSel.append('<button class="dayClass minuteClass" data-minuteindex="' + Minute + '">' + Minute + '</button>');
if (results.d.result[i] == 1)
HourSel.append('<div class="btn on minbutton minuteClass" data-minuteindex="' + Minute + '">' + Minute + '</div>');
else
HourSel.append('<div class="btn minbutton minuteClass" data-minuteindex="' + Minute + '">' + Minute + '</div>');
//if (i == 16)
// oSel.append('<hr style="visibility:hidden;"><div id="dayBreak"> </div>');
}
breakMinutes();
$('.minuteClass').on('click', onMinuteClick);
}
}
});
}
Related
I am running a block of code with the interval of 1 sec which is fine. But I am having an issue that the callback function check_live_records() has an AJAX call and in its success I want to run a block of code just once which I am unable to execute. What can be the possible way to achieve this?
The expectation is that the following code only adds a single row once if there is a new record.
// update bidding table block should run once for each change
var running = false;
var _interval = 1;
if (_interval) {
setInterval(function() {
check_live_records();
}, _interval * 1000);
}
function check_live_records() {
if (typeof running === 'boolean' && running === true) {
return;
}
running = true;
var displayRow = 0; // i tried adding a varibale to control this
$.ajax({
url: ajaxUrl,
type: 'POST',
encoding: 'UTF-8',
dataType: 'JSON',
data: {
action: 'get_live_records',
last_timestamp: last_timestamp
},
success: function(response) {
if (response != null) {
$.each(response.auctions, function(key, value) {
if (key > 0) {
var tableRow = $('tr#auction-' + key);
if (tableRow.length) {
// change current price value
tableRow.find('.column-current_price').html(value.wua_curent_bid);
if (value.table_row) {
if (displayRow == 0) {
// update bidding table
var logs = value.table_row;
console.log(displayRow);
var _row = '<tr>' +
'<td>' + logs.user_display_name + '</td>' +
'<td>' + logs.currency_symbol + logs.current_bid + '</td>' +
'<td>' + logs.currency_symbol + logs.max_bid + '</td>' +
'<td>' + logs.date + '</td>' +
'</tr>';
tableRow.find('table#auction_bidding_table_' + key + ' tbody').prepend(_row);
displayRow + 1;
}
}
}
});
}
running = false;
},
error: function() {
running = false;
}
});
}
I have ajax request below - where it will get a number of pledges (tiles) by users in which when there's a pledge, the tile will flip and show:
var reveal = 0;
$.ajax({
type: 'GET',
dataType: "json",
url: '/Services/getpledge.ashx',
success: function (data) {
if (data.status === "Success") {
$.each(data.Pledges, function (i, v) {
if (typeof v.TileID !== 'undefined') {
jQuery('.square-container div[data-id=' + v.TileID + ']').find('.front div').removeClass('box1').addClass('box3');
jQuery('.square-container div[data-id=' + v.TileID + ']').parent().addClass('complete');
jQuery('.square-container div[data-id=' + v.TileID + ']').attr('data-content', v.PledgeContent);
jQuery('.square-container div[data-id=' + v.TileID + ']').attr('data-smoke', v.isSmoker);
jQuery('.square-container div[data-id=' + v.TileID + ']').attr('data-fb_uid', v.FBID);
if (v.Lastname != null)
jQuery('.square-container div[data-id=' + v.TileID + ']').attr('data-name', v.Firstname + ' ' + v.Lastname);
else
jQuery('.square-container div[data-id=' + v.TileID + ']').attr('data-name', v.Firstname);
}
reveal += 1;
});
//reveal = data.Pledges.length;
//console.log(data.Pledges.length + ' ' + reveal);
$('.changeMe').text(reveal + '/' + number_square);
}
},
error: function () {
console.log('An error has occured, please refresh page and try again');
}
});
On the day of the launch, there will be a number of users using the website simultaneously, so I was wondering how can I make sure the request is done automatically - every 30 seconds so the page always updated.
You could simply do the following which will run every 30 seconds..
window.setInterval(function() {
// code you want to run..
}, 30000);
i have two data attributes one in decreasing every second and is 0 when the first attribute reach 0 an ajax request is send to get the second data value but when i set the value to the second data attribute is not changed in html but when i printed it changed !!!
my code
setInterval(
function () {
if ($j('#auctions-widget .auction_hours').length) {
var auctions_hours = [];
$j('#auctions-widget .auction_hours').each(function () {
auctions_hours.push($j(this).data('auction-id'));
});
for (var i = 0; i < auctions_hours.length; i++) {
checkAuctionHours(auctions_hours[i]);
}
}
}
, 1000);
function checkAuctionHours(auction_id) {
//var TimeWorker = new Date();
var auction_hours = $j("body").find(".auction_hours[data-auction-id='" + auction_id + "']");
if (auction_hours.length) {
//if(auction_id == 1637 && (auction_hours.data("open-contest-hours") !=0 || auction_hours.data("close-contest-hours")!=0) ){
//console.log('time to open-contest-hours: ' + auction_hours.data("open-contest-hours") + ' id= ' + auction_id);
//console.log('time to close-contest-hours: ' + auction_hours.data("close-contest-hours") + ' id= ' + auction_id);
//}
if (auction_hours.data("open-contest-hours") != 0) {
auction_hours.data("open-contest-hours", auction_hours.data("open-contest-hours") - 1);
console.log('time to open-contest-hours: ' + auction_hours.data("open-contest-hours") + ' id= ' + auction_id);
//validate_auctions_hours_time(auction_id, 'open');
//console.log('open');
//console.log(auction_id);
if (auction_hours.data("open-contest-hours") == 0) { //time to open auction based on auction hours
//send the ajax to check;
//console.log('open');
validate_auctions_hours_time(auction_id, 'open');
}
} else if (auction_hours.data("close-contest-hours") != 0) {
auction_hours.data("close-contest-hours", auction_hours.data("close-contest-hours") - 1);
console.log('time to close-contest-hours: ' + auction_hours.data("close-contest-hours") + ' id= ' + auction_id);
//validate_auctions_hours_time(auction_id, 'close');
if (auction_hours.data("close-contest-hours") == 0) { //time to close auction based on auction hours
//send the ajax to check;
//console.log('close');
validate_auctions_hours_time(auction_id, 'close');
}
} else if (auction_hours.data("open-contest-hours") == 0 && auction_hours.data("close-contest-hours") == 0) {
} else {
}
}
}
ajax code
function validate_auctions_hours_time(auction_id, auction_hours_status) {
$.ajax({
async: true,
url: my_ajax_script.ajaxurl,
type: 'POST',
data: ({
type: 'POST',
action: 'validate_auction_hours_time',
auction_id: auction_id,
auction_hours_status: auction_hours_status
}),
success: function (response) {
var auction_hours = $("body").find(".auction_hours[data-auction-id='" + auction_id + "']");
var auction_hours_img = '';
if (response.time_status == 'OK') {
if (response.auction_hours_open_time) { //close auction till next from auction hours
//auction_hours.data('open-contest-hours', response.auction_hours_open_time);
auction_hours.attr('data-open-contest-hours', response.auction_hours_open_time);
console.log(auction_hours.attr('data-open-contest-hours'));
auction_hours_img = $("body").find(".open-hours-active[data-auction-hours-img='" + auction_id + "']");
auction_hours_img.removeClass('open-hours-active');
auction_hours_img.parent().removeClass('auction_hours_blink').removeClass('auction_hours_reset_blink');
auction_hours_img.parent().addClass('auction_hours_blink');
auction_hours_img.addClass('open-hours-deactive');
$('#' + auction_hours_img.data('selector')).html(response.tool_tip);
} else if (response.auction_hours_close_time) { //open auction till next to auction hours
//auction_hours.data('close-contest-hours', response.auction_hours_close_time);
auction_hours.attr('data-close-contest-hours', response.auction_hours_close_time);
console.log(auction_hours.attr('data-close-contest-hours'));
console.log(auction_hours);
auction_hours_img = $("body").find(".open-hours-deactive[data-auction-hours-img='" + auction_id + "']");
auction_hours_img.removeClass('open-hours-deactive');
auction_hours_img.parent().removeClass('auction_hours_blink').removeClass('auction_hours_reset_blink');
auction_hours_img.parent().addClass('auction_hours_blink');
auction_hours_img.addClass('open-hours-active');
$('#' + auction_hours_img.data('selector')).html(response.tool_tip);
}
}
else if (response.time_status == 'RESET') {
if (response.auction_hours_open_time) { //sync auction to auction hours
auction_hours_img = $("body").find(".open-hours-deactive[data-auction-hours-img='" + auction_id + "']");
auction_hours.data('open-contest-hours', response.auction_hours_open_time);
auction_hours_img.parent().removeClass('auction_hours_reset_blink').removeClass('auction_hours_blink');
auction_hours_img.parent().addClass('auction_hours_reset_blink');
} else if (response.auction_hours_close_time) { //sync auction from auction hours
auction_hours_img = $("body").find(".open-hours-active[data-auction-hours-img='" + auction_id + "']");
auction_hours.data('close-contest-hours', response.auction_hours_close_time);
auction_hours_img.parent().removeClass('auction_hours_reset_blink').removeClass('auction_hours_blink');
auction_hours_img.parent().addClass('auction_hours_reset_blink');
} else {
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
response_errors_handling(jqXHR, textStatus, errorThrown);
}
});
finally i try to replace all the auction_hours.data with auction_hours.attr in all the code and it work fine.
I am not very experienced with JavaScript. Please see the code below:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
}
}
}
window.onload = GetSQLTable
</script>
The code incrementally builds a webpage i.e. x number of HTML tables are obtained and displayed to the webpage as and when they become ready. This works.
The problem is I don't know how to remove the LoadingImage once the webpage is complete i.e. $("#LoadingImage").hide();. OnSuccess is called x number of times depending on how many tables are returned so I cannot put it in there.
One way would be to count the number of successful onSuccess() calls, and hide your loading image when they are all complete:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
var numSucceeded = 0;
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
numSucceeded++;
if (numSucceeded === totalrows) {
$("#LoadingImage").hide();
}
}
}
}
}
window.onload = GetSQLTable
</script>
Try using .when with an array of your ajax calls. Something like this (simplified to remove the irrelevant bits):
function GetSQLTable() {
//...
var calls = [];
for (var i = 0; i < res.length; i++) {
//..
calls.push($.ajax({
type: "POST",
//..
}));
}
$.when(calls).then(function(d) {
// all done!!!
});
I have a javascript code as below
var xReg = '<region><width>' + $("#txtWidth").val() + '</width> <height>' + $("#txtHeight").val() + '</height><float>' + $("#floats").val() + '</float><contenttype>' + $("#contenttype").val() + '</contenttype><style>' + rgnStyle + '</style></region>';
$.ajax({
type: "POST",
url: "myurl/addRegion",
data: "{pubId: '" + Number($("#pubs").val()) + "',section: '" + $("#sections option:selected").text() + "',layoutW: '" + Number($("#txtLayoutW").val()) + "',layoutH: '" + Number($("#txtLayoutH").val()) + "',bSubReg: '" + Boolean($("#chkSubRegion").is(':checked')) + "',parentRegId: '" + Number(parentRgn) + "',sXmlRegion: '" + xReg.toString() + "'}",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (result) {
document.body.style.cursor = 'pointer';
if (result.d == -1) {
$("#errMsg").text("Failed to create new region");
}
else {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
},
error: function (result) {
if (result.status == 200 && result.statusText == 'OK') {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
else {
alert("FAILED : " + result.status + ' ' + result.statusText);
}
},
async: true
});
Server code as below
[WebMethod]
public int addRegion(int pubId, string section, int layoutW, int layoutH, bool bSubReg, int parentRegId, string sXmlRegion)
{
string path = Server.MapPath("~");
path = Path.Combine(path, "Published");
path = Path.Combine(path, pubId.ToString());
path = Path.Combine(path, section);
XmlDocument doc = new XmlDocument();
int rgnCount = 0;
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = Path.Combine(path, "layout.xml");
if (!File.Exists(path))
{
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode templateNode = doc.CreateElement("layout");
doc.AppendChild(templateNode);
XmlNode xNodeW = doc.CreateElement("width");
xNodeW.AppendChild(doc.CreateTextNode(layoutW.ToString()));
XmlNode xNodeH = doc.CreateElement("height");
xNodeH.AppendChild(doc.CreateTextNode(layoutH.ToString()));
}
else
{
doc.Load(path);
doc.DocumentElement.SelectSingleNode("/layout/width").InnerText = layoutW.ToString();
doc.DocumentElement.SelectSingleNode("/layout/height").InnerText = layoutH.ToString();
}
XmlElement root = doc.DocumentElement;
XmlNode xParent = root;
if (bSubReg)
{
xParent = root.SelectSingleNode("/layout/region[id='" + parentRegId.ToString() + "']");
rgnCount = xParent.SelectNodes("/region").Count;
}
else
{
rgnCount = root.SelectNodes("/Layout/region").Count;
}
rgnCount++;
XmlDocumentFragment docFragment = doc.CreateDocumentFragment();
docFragment.InnerXml = sXmlRegion;
XmlNode xID = doc.CreateElement("id");
xID.AppendChild(doc.CreateTextNode(rgnCount.ToString()));
docFragment.FirstChild.AppendChild(xID);
xParent.AppendChild(docFragment);
doc.Save(path);
return rgnCount;
}
catch (Exception eX)
{
return -1;
}
}
The call is going to server from client. And no issues I could find in server code till last return statement while I debugged it. In the javascript debugging I found that after ajax call is always going to error callback function. Can anyone suggest whats wrong with the code.
Thanks & Appreciate Your Time.
I found the bug in my code there is issue with below lines of code
},
async: true
at the end of error: callback function
I removed the line async: true and it worked