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 use the Google Places API and when I change address it works perfectly in Chrome but doesn't always work in Mozilla Firefox.
I use jQuery, Bootstrap 4 and JS and Symfony 4 for the backend.
function onPlaceChangedEditUser() {
console.log('1');
var place = this.getPlace();
$('.postal_code').val('');
for (var i in place.address_components) {
var component = place.address_components[i];
for (var j in component.types) {
var type_element = $('.' + component.types[j]);
if (component.types[j] == "country") {
$('#country').find('option').attr('selected', false);
$('#country').find('option[data-country="' + component.short_name + '"]').attr('selected', true);
$('#country_iso').val(component.short_name);
$('#country').change();
$('.country-short').val(component.short_name);
if ($('.country').length) {
$.ajax({
url: Routing.generate("front.dashboardbabysitter.find.language"),
type: "POST",
headers: {
"cache-control": "no-cache"
},
async: false,
cache: false,
data: {
'isoCountry': component.short_name
},
success: function(json) {
if (!json.hasError) {
$('.country option:selected').removeAttr('selected');
$('.country option[value=' + json.idLanguage + ']').attr('selected', 'selected');
$('.country').val(json.idLanguage);
}
},
error: function(XMLHttpRequest, textStatus) {
if (textStatus !== 'abort') {
var error = "TECHNICAL ERROR: unable to send login informations \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus;
$.growl.error({
message: error
});
return false;
}
},
complete: function() {}
});
}
if (jQuery.inArray(component.short_name, mp_country_prefix)) {
var phone_number = '+' + mp_country_prefix[component.short_name];
var flag_class = (component.short_name).toLowerCase();
$('#flag').removeClass().addClass('flag position-absolute ' + flag_class);
$('#phone').val(phone_number);
} else {
console.log('there is no iso');
}
}
if (type_element) {
type_element.val(component.long_name);
}
if ($("#latitude").length) {
$("#latitude").val(place.geometry.location.lat());
$("#longitude").val(place.geometry.location.lng());
}
if ($(".latitude").length) {
$(".latitude").val(place.geometry.location.lat());
$(".longitude").val(place.geometry.location.lng());
}
if ($('#address1').length) {
$('#address1').val($('.street_number').val() + ' ' + $('.route').val())
}
if ($('#edit_babysitter_personal_info_address_address1').length) {
$('#edit_babysitter_personal_info_address_address1').val($('.street_number').val() + ' ' + $('.route').val())
}
if ($('#parent_personal_info_address_address1').length) {
$('#parent_personal_info_address_address1').val($('.street_number').val() + ' ' + $('.route').val())
}
}
}
}
function initializeAutocomplete(id) {
var element = document.getElementById(id);
if (element) {
var autocomplete = new google.maps.places.Autocomplete(element, {
types: ['geocode'],
language: _mpop.current_lang
});
if (id == "parent_personal_info_fullAddress" || id == "edit_babysitter_personal_info_fullAddress" ||
id == "address_bb" || id == "home_address") {
google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChangedEditUser);
}
}
}
You can use addEventListener instead of addListener
Reference - link
Identify the browser and apply the event accordingly.
I have a javascript function which is load help menu list (dropdown).
First function: GetPageKeyword()
function GetPageKeyword() {
var url = window.location.href.replace(window.location.origin, '').replace('/#', '').replace('#', '').replace('//', '/');
url = url.split("?")[0];
url = GetURL(url);
if (url.lastIndexOf('/') == (url.length - 1))
url = url.slice(0, -1);
if (url.indexOf('/') == 0)
url = url.substring(1, url.length);
$.ajax({
url: "/api/PageKeywords/GetLabelsByUrl",
type: 'Get',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
data: { url: url },
success: function (data) {
var res = data.data;
var htmlAppend = '<a id="hlpMenuLink" class="dropdown-toggle" data-toggle="dropdown"><i style="font-size: 17px;" class="fa fa-question-circle"></i></a>';
if (res.length > 0) {
$.getJSON("https://test.com/search.json?label_names=" + res[0].labels,
function (data) {
if (data.results.length > 0) {
htmlAppend += '<ul id="menuHelpUl" class="dropdown-menu pull-right">';
for (var i = 0; i < data.results.length; i++) {
htmlAppend += "<li>" + data.results[i].name + "</li>";
}
htmlAppend += "</ul>";
}
$('#helpMenu').html(htmlAppend);
});
}
$('#helpMenu').html(htmlAppend);
setTimeout(function () { GetArticulateDetails(); }, 1100);
},
error: function (jqXhr, textStatus, errorThrown) {
var err = jqXhr;
}
});
}
But now I need to add more item to help menu.
In the second function I tried to add the new item to ul id="menuHelpUl" which I build in the first function.
Second function: GetArticulateDetails()
function GetArticulateDetails() {
var url = window.location.href.replace(window.location.origin, '').replace('/#', '').replace('#', '').replace('//', '/');
url = url.split("?")[0];
url = GetURL(url);
if (url.lastIndexOf('/') == (url.length - 1))
url = url.slice(0, -1);
if (url.indexOf('/') == 0)
url = url.substring(1, url.length);
$.ajax({
url: "/api/PageKeywords/GetArticulateLabelByUrl",
type: 'Get',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
data: { url: url },
success: function (data) {
var res = data.data;
var htmlAppend = '<hr/>';
if (res.length > 0) {
for (var i = 0; i < res.length; i++) {
htmlAppend += "<li>" + res[i].name + "</li>";
}
}
$('#menuHelpUl').append(htmlAppend);
},
error: function (jqXhr, textStatus, errorThrown) {
var err = jqXhr;
console.log(err);
}
});
}
In first function GetPageKeyword at last on success response, i am calling the second function which is
setTimeout(function () { GetArticulateDetails(); }, 1100);
Here I am having problem some case the second function is not working because it may be it can not find id of #helpMenu.
code : function : GetArticulateDetails :-- $('#helpMenu').html(htmlAppend);
So there how I call my second funtion after compleate first function.
Try to call your second function right in the end of your ajax success callback:
$.ajax({
/* settings */
success: function (data) {
var res = data.data;
var htmlAppend = '<a id="hlpMenuLink" class="dropdown-toggle" data-toggle="dropdown"><i style="font-size: 17px;" class="fa fa-question-circle"></i></a>';
if (res.length > 0) {
$.getJSON("https://test.com/search.json?label_names=" + res[0].labels,
function (data) {
if (data.results.length > 0) {
htmlAppend += '<ul id="menuHelpUl" class="dropdown-menu pull-right">';
for (var i = 0; i < data.results.length; i++) {
htmlAppend += "<li>" + data.results[i].name + "</li>";
}
htmlAppend += "</ul>";
}
$('#helpMenu').html(htmlAppend);
GetArticulateDetails(); // here !
});
}
$('#helpMenu').html(htmlAppend);
}
});
Also, maybe it would be necessary to protect this call by
if (data.results.length > 0) {
GetArticulateDetails();
}
declare the menuHelpUl as a ui element like this:
var menuHelpUl = $('<ul id="menuHelpUl" class="dropdown-menu pull-right">');
and append li elements to it in loop
var li = $("<li>" + data.results[i].name + "</li>");
menuHelpUl .append(li);
now pass the menuHelpUl to GetArticulateDetails in ajax success:
GetArticulateDetails(menuHelpUl);
and use it in ajax success
menuHelpUl.append(htmlAppend);
In your first method the call
$('#helpMenu').html(htmlAppend)
Should be inside the handler for getJson(...)
Currently it is called before that method completes but relies on data generated by that async callback.
(I'd give you an explicit code change but difficult to edit on mobile)
Edit - actually the above line is duplicated. The one outside the handler can be removed. Perhaps there are duplicate Ids?
You can also call the second method from within the getJson handler after the Html has been updated.
menuHelpUl will only exist if the call in getJson returns some data. If it does not, there will be no element.
Try this solution using promises in javascript:
function GetPageKeyword() {
return new Promise((resolve, reject)=>{
//your code here
resolve();
});
}
function GetArticulateDetails() {
return new Promise((resolve, reject)=>{
//your code here
resolve();
});
}
Call it like this:
GetPageKeyword().then((result)=>{
GetArticulateDetails();
}).catch((error)=>{
//handle error
});
here is the edited first function :
function GetPageKeyword() {
return new Promise((resolve,reject)=>{
var url = window.location.href.replace(window.location.origin, '').replace('/#', '').replace('#', '').replace('//', '/');
url = url.split("?")[0];
url = GetURL(url);
if (url.lastIndexOf('/') == (url.length - 1))
url = url.slice(0, -1);
if (url.indexOf('/') == 0)
url = url.substring(1, url.length);
$.ajax({
url: "/api/PageKeywords/GetLabelsByUrl",
type: 'Get',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
data: { url: url },
success: function (data) {
var res = data.data;
var htmlAppend = '<a id="hlpMenuLink" class="dropdown-toggle" data-toggle="dropdown"><i style="font-size: 17px;" class="fa fa-question-circle"></i></a>';
if (res.length > 0) {
$.getJSON("https://test.com/search.json?label_names=" + res[0].labels,
function (data) {
if (data.results.length > 0) {
htmlAppend += '<ul id="menuHelpUl" class="dropdown-menu pull-right">';
for (var i = 0; i < data.results.length; i++) {
htmlAppend += "<li>" + data.results[i].name + "</li>";
}
htmlAppend += "</ul>";
$('#helpMenu').html(htmlAppend);
resolve()
}else{
$('#helpMenu').html(htmlAppend);
resolve()
}
});
}else{
$('#helpMenu').html(htmlAppend);
resolve()
}
},
error: function (jqXhr, textStatus, errorThrown) {
var err = jqXhr;
reject()
}
});
})
}
You can use jquery.when
$.when(GetPageKeyword()).then(GetArticulateDetails());
from the code it seems like $('#helpMenu') is found to be null or undefined.
try to check the null or undefind status of $('#helpMenu')
**if($('#helpMenu') == null || $('#helpMenu') == undefined)**
and then perform the append html operation.
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'm getting a "Uncaught SyntaxError: Unexpected end of input" error, when i take out the below snippet the error goes away. Maybe its because ive been up all night but i cant for the life of me find the issue. Can anyone please shed some light?
$.ajax({
url: "scripts/getWorkerPendingJobs.php",
type: "get",
data: {uid: userId},
success: function(dataa) {
var daa = JSON.parse(dataa);
var amtt = parseInt(daa.length);
var htmll = "";
if (amtt > 0) {
$.each(daa, function(indexx) {
var status;
var acc = daa[indexx].accepted.toString();
if (acc == 1) {
status = "Pending";
}
if (acc == 2) {
status = "Accepted";
}
htmll += '<li><img src="./noimage.png" /><h3>' + daa[indexx].dateadded + ' | ' + daa[indexx].shortdesc + '</h3><h2>Status : ' + status + '</h2><p>' + daa[indexx].description + '</p></li>';
$('.worker-applied-jobs').html(htmll).promise().done(function() {
$(this).listview("refresh");
});
});
} else {
$('.worker-applied-jobs').html('<p style="margin-left:10px;">You have not applied for any jobs.</p>');
}
}
});