In setInterval() a block of code should run once - javascript

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

Related

How do I assign an event to an input and checkbox made of n counts?

I'm a spring beginner. I'm currently updating the data in db. The current db data I need is as follows.
UPDATE
MY_DB
SET type_big_category = type_big_category
<if test="status != ''">
, status = #{status}
</if>
<if test="body != null">
, body = #{body}
</if>
WHERE
seq_no = #{seq_no}
And the list is being printed from js file by running a repeat statement.
$(function() {
$.ajax({
url : "/dblistdata",
type : "GET",
dataType : "json",
data: data,
timeout: 10000
}).done(function (result) {
if(result.resultCode == "S000"){
for (var i = 0; i < result.messagelist.length; i++) {
var tableBody = '<tr>'
+ '<td>' + result.messagelist[i].type_big_category + '</td>'
+ '<td>' + result.messagelist[i].type_mid_category + '</td>'
+ '<td>'
+ '<label class="checkbox" for="checkbox' + i + '">'
+ '<input type="checkbox" name="checkbox'+ i +'" id="checkbox' + i + '" onClick="checkBoxClick(this.name, '+ result.messagelist[i].seq_no +')" />' + '<i>' + '</i>'
+ '</label>'
+ '</td>'
+ '<td>'
+ '<textarea class="form-control push-text">"' + result.messagelist[i].body + '"</textarea>'
+ '</td>'
+ '<td>'
+ '<button type="button" class="btn btn-primary">save</button>'
+ '<button type="button" class="btn btn-default" id="deletebutton'+ i + '">delete</button>'
+ '</td>'
+ '</tr>';
$('#tbody').append(tableBody);
var btn[i] = document.getElementById('deletebutton[i]');
btn[i].disabled = 'disabled';
}
}else{
alert(result.resultMsg);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
})
});
function saveCommentData(seq_no, comment) {
alert(seq_no);
}
function checkBoxClick(id, seq_no) {
var data = {};
data.seq_no = seq_no;
console.log("id : " + id + " / seq_no " + seq_no);
let check = $("#" + id).is(":checked");
if (check == false) {
var activecheck = confirm('Are you sure you want to disable it??');
if (activecheck == true) {
data.status = '0';
updateStatus(data)
} else {
location.reload();
}
} else {
var activecheck = confirm('Do you want to activate?');
if (activecheck == true) {
data.status = '1';
updateStatus(data)
} else {
location.reload();
}
}
}
function updateStatus(data) {
$.ajax({
url : "/v1/point/admin/push/update_push_message_status",
type : "POST",
dataType : "json",
data : data,
success : function(result) {
console.log(result);
}
})
location.reload();
}
jsp
<form class="smart-form">
<table class="tb-regist" id="autoPushMsg">
<thead>
<tr>
<th>main</th>
<th>sub</th>
<th>check</th>
<th colspan="2">mssage</th>
</tr>
</thead>
<tbody id="tbody">
...
The blockage I have is db, the current status value is all 1 except one. Therefore, only one check should be disabled, and all the rest should be checked.
I must change the body value, i.e. the message value, and change the status when I press the Save button.
I'm done with the db design, but I don't know how to change the order and activate/disable the check.
Thank you for your help. I need your solution.
The section on the indication of the check box status was resolved by inserting it into the repeat statement.
if(result.messagelist[i].status == '0') {
document.getElementById("checkbox" + i).checked = false;
}else{
document.getElementById("checkbox" + i).checked = true;
}
Thus, the check box status update function was completed and the index value of the corresponding row was received and resolved when the message value was updated.
function saveCommentData(seq_no, index) {
var activecheck = confirm('change message save?');
var data = {}
data.seq_no = seq_no;
var comment = $("#comment" + index).val();
data.body = comment
if (activecheck == true) {
updateStatus(data);
} else {
location.reload();
}
}

problems with storing getjson request in variable

I'm having troubles with getting a variable from a getJSON() request. I have the following three functions:
function getPcLatitude() { // onchange
var funcid = "get_postcode_latitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLatitude) {
if (dataLatitude == null) {
//..
} else {
var myLatitude = 0;
for (var i=0;i<dataLatitude.length;i++){
myLatitude = dataLatitude[i].pc_latitude;
}
return parseFloat(myLatitude);
//alert(myLatitude);
}
});
}
function getPcLongitude() { // onchange
var funcid = "get_postcode_longitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLongitude) {
if (dataLongitude == null) {
//..
} else {
var myLongitude = 0;
for (var i=0;i<dataLongitude.length;i++){
myLongitude = dataLongitude[i].pc_longitude;
}
return parseFloat(myLongitude);
//alert(myLongitude);
}
});
}
function getTop5Postcode() { // onchange
setTimeout(function() {
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var latitude = getPcLatitude();
var longitude = getPcLongitude();
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}, 0);
}
Form some reason the
var latitude = getPcLatitude();
var longitude = getPcLongitude();
parts don't work / don't get a value form the functions. When I change the return in both functions into an alert() it does give me the expected values, so those two functions work.
When I set the two variables directly, like so:
var latitude = 5215;
var longitude = 538;
then the getTop5Postcode() function does work and fills the table.
Any help on this?
Regards, Bart
Do not forget that JavaScript is asynchronous, so by the time you reach the return statement, the request is probably not done yet. You can use a promise, something like:
$.getJSON(....).then(function(value){//do what you want to do here})
Both your functions (getPcLatitude and getPcLongitude) are returning nothing because the return statement is inside a callback from an asynchronous request, and that's why an alert show the correct value.
I would suggest you to change both methods signature adding a callback parameter.
function getPcLatitude(callback) {
...
}
function getPcLongitude(callback) {
...
}
And instead of returning you should pass the value to the callback:
callback(parseFloat(myLatitude));
callback(parseFloat(myLongitude));
And your last function would be somehting like that:
function getTop5Postcode() { // onchange
setTimeout(function() {
var latitude;
var longitude;
getPcLatitude(function(lat) {
latitude = lat;
getTop5(); // Here you call the next function because you can't be sure what response will come first.
});
getPcLongitude(function(longi) {
longitude = longi;
getTop5();
});
function getTop5() {
if (!latitude || !longitude) {
return; // This function won't continue if some of the values are undefined, null, false, empty or 0. You may want to change that.
}
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}
}, 0);
}
Of course, this is far away from the perfect solution for your problem but it should work!
And I did not test this code.
I solved this by doing some extra stuff in mysql queries. Now I only have to use the main function.
Things work now! Thanks for all the help!

Jquery Ajax Call always returns error

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

Data fetched from JSON not getting updated

Below is the script:
$(document).ready(function () {
$.getJSON('table.json', function (data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
});
});
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000);
});
}
I want to update my data. The poll function is getting called after every 5 seconds which I checked through the alert. But data is not getting updated. Please tell me what I am doing wrong.
getJSON is a GET request so it will be cached. Set the proper no cache headers on the server.
Also look at your code, you are never processing the data
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000); //<--where is the processing you do nothing with the response???
});
}
$(document).ready(function() {
// make the initial JSON request
$.getJSON('table.json', init)
});
function poll() {
// make the subsequent JSON requests
$.getJSON('dummy.json', update);
}
function init(data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
}
function update(data) {
var rows = $("#mytable tr.tablecontent").toArray();
for (var i = 0, size = data.length; i < size; i++) {
if (rows[i])
rows[i].cells[3].firstChild.data = data[i].bid;
}
setTimeout(poll, 5000);
}
Here's the update function with more jQuery:
function update(data) {
$("#mytable tr.tablecontent > td:nth-child(4)")
.slice(0, data.length)
.text(function(i) {
return data[i].bid;
});
setTimeout(poll, 5000);
}

problem ajax load with autocomplete.?

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Categories

Resources