i send ajax request every 5 second and i want wait for next requset until the previous one is done ...
Because it sends a lot of requests even if the status of the previous request is pending, and this causes me a problem with the server.
this is my Java Script code :
this is my Java Script code :
$(document).ready(function(e){
$("#getUsersId").on('submit', function(e){
e.preventDefault();
$('.loading_spinner').css('display','flex');
$('.form-fieldset.api-mode').attr('disabled','disabled');
let id = 1;
let zeroNum = "0";
var keyword = $('#keyword').val();
var region = $('#region').val();
// you can use a "fat-arrow" function or a function reference, look at the docs
let timer = 5000;
// console.log(timer);
const interval = setInterval(() => {
if (id>=9) {
let zeroNum = "";
}
$.ajax({
type: "post",
url: "dataExtractorRequset.php",
data: {keyword: keyword,region: region,id:id},
dataType: 'json',
success: function (response) {
// var parsedJson= JSON.parse(response);
// console.log(response);
function countTextArea() {
var text = $("#FbUsersId").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length-1;
return count;
}
var output2 = "";
if(response.status == 1){
clearInterval(interval);
$('.successMSG').html(Swal.fire({
icon: 'success',
title: response.message,
showConfirmButton: true,
timer: 3000,
timerProgressBar: true
})
);
$('.loading_spinner').css('display','none');
$('.form-fieldset.api-mode').removeAttr('disabled');
$('#sendForm').css('display','block');
var arr = $("#FbUsersId").val().split("\n");
var arrDistinct = new Array();
$(arr).each(function(index, item) {
if ($.inArray(item, arrDistinct) == -1)
arrDistinct.push(item);
});
var newUniquData = arrDistinct;
$.each(newUniquData, function(key, value) {
output2 += value+'\r\n';
});
$("#FbUsersId").val(output2);
$('#usersCount').html(countTextArea);
var text = $('#FbUsersId').val();
text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
$(FbUsersId).val(text);
console.log("success");
console.log(arrDistinct);
alert("Done !!!");
}else{
var output = "";
for (i =0; i< response.length; i++) {
console.log(response[i].data.user_url);
output += response[i].data.user_url+ '\r\n';
}
// var appendData = $("#FbUsersId").val();
// var newData = appendData + output;
$("#FbUsersId").append(output);
$('#usersCount').html("Loading...");
if(response.status == 0) {
$('.loading_spinner').css('display','none');
$('.form-fieldset.api-mode').removeAttr('disabled');
clearInterval(interval);
$('.successMSG').html(Swal.fire({
icon: 'error',
title: response.message,
text: response.errMSG,
showConfirmButton: true,
timer: 10000,
timerProgressBarColor: '#435ebe',
timerProgressBar: true
}).then(function(isConfirm) {
if (isConfirm) {
// location.reload();
} else {
//if no clicked => do something else
}
})
);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
// console.log(textStatus, errorThrown);
}
});
id++;
// stop the interval when id is greater 9
// if (id > 9) {
// }
}, timer); // 3000 is the time in milliseconds
});
});
How can I solve this problem.
Not so elegant (I would set setTimeout) but as Barmar suggested a global variable is quick solution:
$(document).ready(function (e) {
$("#getUsersId").on('submit', function (e) {
e.preventDefault();
$('.loading_spinner').css('display', 'flex');
$('.form-fieldset.api-mode').attr('disabled', 'disabled');
let id = 1;
let zeroNum = "0";
var keyword = $('#keyword').val();
var region = $('#region').val();
// you can use a "fat-arrow" function or a function reference, look at the docs
let timer = 10000;
// console.log(timer);
var in_progress
const interval = setInterval(() => {
if (in_progress) {
return;
}
in_progress = true;
if (id >= 9) {
let zeroNum = "";
}
$.ajax({
type: "post",
url: "dataExtractorRequset.php",
data: { keyword: keyword, region: region, id: id },
dataType: 'json',
success: function (response) {
in_progress = false;
// var parsedJson= JSON.parse(response);
// console.log(response);
function countTextArea() {
var text = $("#FbUsersId").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length - 1;
return count;
}
var output2 = "";
if (response.status == 1) {
clearInterval(interval);
$('.successMSG').html(Swal.fire({
icon: 'success',
title: response.message,
showConfirmButton: true,
timer: 3000,
timerProgressBar: true
})
);
$('.loading_spinner').css('display', 'none');
$('.form-fieldset.api-mode').removeAttr('disabled');
$('#sendForm').css('display', 'block');
var arr = $("#FbUsersId").val().split("\n");
var arrDistinct = new Array();
$(arr).each(function (index, item) {
if ($.inArray(item, arrDistinct) == -1)
arrDistinct.push(item);
});
var newUniquData = arrDistinct;
$.each(newUniquData, function (key, value) {
output2 += value + '\r\n';
});
$("#FbUsersId").val(output2);
$('#usersCount').html(countTextArea);
var text = $('#FbUsersId').val();
text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
$(FbUsersId).val(text);
console.log("success");
console.log(arrDistinct);
alert("Done !!!");
} else {
var output = "";
for (i = 0; i < response.length; i++) {
console.log(response[i].data.user_url);
output += response[i].data.user_url + '\r\n';
}
// var appendData = $("#FbUsersId").val();
// var newData = appendData + output;
$("#FbUsersId").append(output);
$('#usersCount').html("Loading...");
if (response.status == 0) {
$('.loading_spinner').css('display', 'none');
$('.form-fieldset.api-mode').removeAttr('disabled');
clearInterval(interval);
$('.successMSG').html(Swal.fire({
icon: 'error',
title: response.message,
text: response.errMSG,
showConfirmButton: true,
timer: 10000,
timerProgressBarColor: '#435ebe',
timerProgressBar: true
}).then(function (isConfirm) {
if (isConfirm) {
// location.reload();
} else {
//if no clicked => do something else
}
})
);
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
// console.log(textStatus, errorThrown);
in_progress = false;
}
});
id++;
// stop the interval when id is greater 9
// if (id > 9) {
// }
}, timer); // 3000 is the time in milliseconds
});
});
Related
Here the first script is written for lazy loading the table data and the second script is written for filtering with lazy loading but the second one is not working.
I have a Codeigniter report in which I did some filtering on the table data. I am using jQuery AJAX to lazy load data. What I expected is that when I fetch the data with a filter the lazy loading is not working. Shall i use first script for both table load by default and for filter. i am getting confusion. Can anyone please tell me how to merge both script as a single script for both. Please help.
$(document).ready(function() {
$('#filter').popover({
placement: 'bottom',
title: (' ') + '<button type="button" class="close pull-right" data-dismiss="alert" style="color:black;">×</button>',
html: true,
content: $('#customdiv').html()
});
$(document).on("click", ".popover .close", function() {
$(this).parents(".popover").popover('hide');
});
var limit = 20;
var start = 0;
var action = 'inactive';
function lazzy_loader(limit) {
var output = '';
for (var count = 0; count < limit; count++) {
output += '<tr class="post_data">';
output += '</tr>';
}
$('#load_data_message').html(output);
}
lazzy_loader(limit);
function search_fields(limit, start) {
$(".spinner").show();
$.ajax({
url: "<?=base_url()?>missed_call_campaign/fetch_data",
method: "POST",
data: {
limit: limit,
start: start
},
cache: false,
success: function(data) {
$(".spinner").hide();
if (data == '') {
$('#load_data_message').html('<p class="content-desc">No More Data Found</p>');
action = 'active';
} else {
$('#load_data').append(data);
$('#load_data_message').html("");
action = 'inactive';
}
}
});
}
if (action == 'inactive') {
action = 'active';
search_fields(limit, start);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive') {
lazzy_loader(limit);
action = 'active';
start = start + limit;
setTimeout(function() {
search_fields(limit, start);
}, 100);
}
});
});
function subcategory() {
var ClickedCategory = new Array();
$('.CategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedCategory.push($(this).val());
}
});
$.ajax({
type: 'POST',
url: "<?=base_url()?>missed_call_campaign/subcategory_checkbox",
data: {
type: 'text',
ClickedCategory: ClickedCategory
},
success: function(response) {
$("#collapsepp").hide();
$("#collapseqq").html(response);
}
});
}
function subsource() {
var ClickedSource = new Array();
$('.SourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSource.push($(this).val());
}
});
$.ajax({
type: 'POST',
url: "<?=base_url()?>missed_call_campaign/subsource_checkbox",
data: {
type: 'text',
ClickedSource: ClickedSource
},
success: function(response) {
$("#collapserr").hide();
$("#collapsess").html(response);
}
});
}
function clearFilter() {
location.reload();
}
$(document).ready(function() {
$(document).on("click", "#data_filter", function() {
var CheckedRep = new Array();
var ClickedStatus = new Array();
var ClickedType = new Array();
var ClickedCategory = new Array();
var ClickedSubCategory = new Array();
var ClickedSubCategory_Filter = new Array();
var ClickedSource = new Array();
var ClickedSubSource = new Array();
var ClickedSubSource_Filter = new Array();
$('.RepClicked').each(function() {
if ($(this).is(':checked')) {
CheckedRep.push($(this).val());
}
});
$('.StatusClicked').each(function() {
if ($(this).is(':checked')) {
ClickedStatus.push($(this).val());
}
});
$('.TypeClicked').each(function() {
if ($(this).is(':checked')) {
ClickedType.push($(this).val());
}
});
$('.CategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedCategory.push($(this).val());
}
});
$('.SourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSource.push($(this).val());
}
});
$('.SubSourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSubSource.push($(this).val());
}
});
$('.SubCategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSubCategory.push($(this).val());
}
});
$('.SubCategoryChecked_Filter').each(function() {
if ($(this).is(':checked')) {
ClickedSubCategory_Filter.push($(this).val());
}
});
$('.SubSourceClicked_filter').each(function() {
if ($(this).is(':checked')) {
ClickedSubSource_Filter.push($(this).val());
}
});
if ((CheckedRep.length > 0) || (ClickedStatus.length > 0) || (ClickedType.length > 0) || (ClickedCategory.length > 0)
(ClickedSource.length > 0) || (ClickedSubSource.length > 0) || (ClickedSubCategory.length > 0) ||
(ClickedSubCategory_Filter.length > 0) || (ClickedSubSource_Filter.length > 0)) {
var limits = 20;
var starts = 0;
var actions = 'inactive';
lazzy_loading(limits);
if (actions == 'inactive') {
actions = 'active';
filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $("#load_data_filter").height() && actions == 'inactive') {
lazzy_loading(limits);
actions = 'active';
starts = starts + limits;
setTimeout(function() {
filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter);
}, 100);
}
});
}
});
function lazzy_loading(limits) {
var output = '';
for (var counts = 0; counts < limits; counts++) {
output += '<tr class="post_data">';
output += '</tr>';
}
$('#load_data_filter').html(output);
}
function filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter) {
$.ajax({
url: "<?=base_url()?>missed_call_campaign/toDoAjax",
method: "POST",
data: {
type: 'text',
CheckedRep: CheckedRep,
ClickedStatus: ClickedStatus,
ClickedType: ClickedType,
ClickedCategory: ClickedCategory,
ClickedSource: ClickedSource,
ClickedSubSource: ClickedSubSource,
ClickedSubCategory: ClickedSubCategory,
ClickedSubCategory_Filter: ClickedSubCategory_Filter,
ClickedSubSource_Filter: ClickedSubSource_Filter,
limits: limits,
starts: starts
},
cache: false,
success: function(response) {
$(".spinner").hide();
$("#load_data").hide();
if (response == '') {
$('#load_data_message').html('<p class="content-desc">No More Data Found123</p>');
action = 'active';
} else {
$('#load_data_filter').append(response);
$('#load_data_message').html("");
action = 'inactive';
}
}
});
}
});
I suggest you to reinitialize the lazy load after success you fetched data from the back end.
For the following code, the emailCnt is 50 for first iteration, I need 25 in next iteration. What is the possible way to access the variable value outside the ajax success and break the for loop execution?
var limit = 50;
var emailCnt = limit;
for (var i = 0; i < 20; i++) {
console.log(emailCnt);///this value is 50 instead I need 25
if (emailCnt < limit && i != 0) {
break;
}
setTimeout(function () {
submit_post(slNo, limit, function (output) {
slNo = output;
emailCnt = 25;
$('#load_data').html('Hello');
});
}, 1000);
}
function submit_post(slNo, limit, handleData) {
$.ajax({
type: 'POST',
async: false,
url: url,
data: { slNo: slNo, limit: limit },
success: function (data) { handleData(data); }
});
}
This successfully worked for me
var limit = 50;
var emailCnt = limit;
function submit_post(slNo, limit)
{
var result="";
$.ajax({
type: 'POST',
async: false,
url: url,
data: {slNo:slNo, limit:limit},
success: function(data) { result = data; }
});
return result;
}
for(var i=0;i<20;i++)
{
if(emailCnt < limit && i != 0)
{
break;
}
setTimeout(function () {
var output = submit_post(slNo, limit);
slNo = output;
emailCnt = 25;
$('#load_data').html('Hello');
}, 1000);
}
This thing always return false on me.
$.validator.unobtrusive.adapters.add('appointmentvalidating', ['daylimit'], function (options) {
options.rules['appointmentvalidating'] = options.params;
options.messages.appointmentvalidating = options.message;
});
$.validator.addMethod('appointmentvalidating', function (value, element, params) {
var dtnow = new Date(Date.parse(value));
var daylimit = parseInt(params.daylimit.toString());
var count = 0;
count = request(dtnow);
if (count < daylimit) {
console.log("true");
return true;
}
if (count >= daylimit) {
console.log("true");
return false;
}
});
function request(dtnow) {
$.ajax({
url: "/api/webapi/",
type: "GET",
async: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var count = 0;
for (var i = 0; i < data.length; i++) {
var datentbproc = data[i].Date;
var datentbproccor = new Date(Date.parse(datentbproc.toString().substr(5, 2) + '/' + datentbproc.toString().substr(8, 2) + '/' + datentbproc.toString().substr(0, 4)));
if (datentbproccor.getFullYear() == dtnow.getFullYear() && datentbproccor.getMonth() == dtnow.getMonth() && datentbproccor.getDate() == dtnow.getDate()) {
count = count + 1;
}
}
return count;
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('request is failed');
},
timeout: 120000,
});
}
But when I use synchronous requests like this it does return false,true as I want.
$.validator.unobtrusive.adapters.add('appointmentvalidating', ['daylimit'], function (options) {
options.rules['appointmentvalidating'] = options.params;
options.messages.appointmentvalidating = options.message;
});
$.validator.addMethod('appointmentvalidating', function (value, element, params) {
var dtnow = new Date(Date.parse(value));
var daylimit = parseInt(params.daylimit.toString());
var count = 0;
$.ajax({
url: "/api/webapi/",
type: "GET",
async: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
for (var i = 0; i < data.length; i++) {
var datentbproc = data[i].Date;
var datentbproccor = new Date(Date.parse(datentbproc.toString().substr(5, 2) + '/' + datentbproc.toString().substr(8, 2) + '/' + datentbproc.toString().substr(0, 4)));
if (datentbproccor.getFullYear() == dtnow.getFullYear() && datentbproccor.getMonth() == dtnow.getMonth() && datentbproccor.getDate() == dtnow.getDate()) {
count = count + 1;
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('request is failed');
},
timeout: 120000,
});
if (count >= daylimit) {
return false;
}
else if (count < daylimit) {
return true;
}
});
As you can see I used If block outside in synchronous request. I tried lot of things. Any of them did not work. If someone face the similar problem and solved can help me I think.
What to do now?
I have a script that pulls data from my CMS and then allows a person to vote on a poll. The script works fine. However, I have Ad Block Plus Plugin installed in Firefox. When that is enabled to blocks the script from submitting the form correctly. It appears to submit correctly in the front end but is never registered in the back end.
Why does Ad Block Plus block my script that has nothing to do with ads?
The script is below:
$(document).ready(function () {
var Engine = {
ui: {
buildChart: function() {
if ($("#pieChart").size() === 0) {
return;
}
var pieChartData = [],
totalVotes = 0,
$dataItems = $("ul.key li");
// grab total votes
$dataItems.each(function (index, item) {
totalVotes += parseInt($(item).data('votes'));
});
// iterate through items to draw pie chart
// and populate % in dom
$dataItems.each(function (index, item) {
var votes = parseInt($(item).data('votes')),
votePercentage = votes / totalVotes * 100,
roundedPrecentage = Math.round(votePercentage * 10) / 10;
$(this).find(".vote-percentage").text(roundedPrecentage);
pieChartData.push({
value: roundedPrecentage,
color: $(item).data('color')
});
});
var ctx = $("#pieChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx).Pie(pieChartData, {});
}, // buildChart
pollSubmit: function() {
if ($("#pollAnswers").size() === 0) {
return;
}
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button"),
bcField_1 = "CAT_Custom_1",
bcField_2 = "CAT_Custom_2",
bcField_3 = "CAT_Custom_3",
$formSubmitData = "";
$radioOptions.on("change", function() {
$formButton.removeAttr("disabled"); // enable button
var chosenField = $(this).data("field"), // gather value
answer_1 = parseInt($existingDataWrapper.data("answer-1")),
answer_2 = parseInt($existingDataWrapper.data("answer-2")),
answer_3 = parseInt($existingDataWrapper.data("answer-3"));
if (chosenField == bcField_1) {
answer_1 = answer_1 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_2) {
answer_2 = answer_2 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_3) {
answer_3 = answer_3 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
prepForm($formSubmitData);
});
function prepForm(formSubmitData) {
$formButton.click(function(e) {
e.preventDefault();
logAnonUserIn("anon", "anon", formSubmitData); // log user in
}); // submit
} // prepForm
function logAnonUserIn(username, password, formSubmitData) {
$.ajax({
type: 'POST',
url: '/ZoneProcess.aspx?ZoneID=-1&Username=' + username + '&Password=' + password,
async: true,
beforeSend: function () {},
success: function () {},
complete: function () {
fireForm(formSubmitData);
}
});
} // logAnonUserIn
function fireForm(formSubmitData) {
// submit the form
var url = "/CustomContentProcess.aspx?A=EditSave&CCID=13998&OID=3931634&OTYPE=35";
$.ajax({
type: 'POST',
url: url,
data: formSubmitData,
async: true,
success: function () {},
error: function () {},
complete: function () {
window.location = "/";
}
});
}
} // pollSubmit
} // end ui
};
Engine.ui.buildChart();
Engine.ui.pollSubmit();
});
As it turns out easylist contains this filter:
.aspx?zoneid=
This is why my script is being blocked.
I was told I can try this exception filter:
##||example.com/ZoneProcess.aspx?*$xmlhttprequest
I could also ask easylist to add an exception.
Answer comes from Ad Block Plus Forums.
I have the following script on my page, in Chrome, it works perfectly, but IE is not getting into the success{} function of Ajax. It goes into the Complete{} function perfectly fine. When I tried to send the data variable through the Complete{} function, it just displays an [object Object] as the contents. What can I do to get this to function in IE?
$(document).ready(function () {
var totalstrings = "";
var totaltimes = "";
var trendstop = "false";
var firstrun = "true";
var url = "newtrend.aspx";
$('#fm1').attr('src', "http://somepage/page1/collecttrend.aspx");
(function worker() {
var rand;
$.ajax({
url: 'http://somepage/page1/gettrendvars.aspx',
success: function (data) {
if (totalstrings.length < data.length || data === "") {
alert("test1");
if (trendstop === "false") {
alert("test2");
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
},
complete: function (data) {
setTimeout(worker, 10000);
$.ajax({
url: 'http://somepage/page1/gettimevars.aspx',
success: function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
},
complete: function (data) {
}
})();
}
});
})();
});
Try adding a timestamp to your ajax requests, for some reason, IE caches it sometimes.
$.ajax({
url: 'http://somepage/page1/gettrendvars.aspx?timestamp='+ new Date().getTime(),
success: function (data) {
if (totalstrings.length < data.length || data === "") {
alert("test1");
if (trendstop === "false") {
alert("test2");
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
},
complete: function (data) {
setTimeout(worker, 10000);
$.ajax({
url: 'http://somepage/page1/gettimevars.aspx?timestamp=' + new Date().getTime(),
success: function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
},
complete: function (data) {
}
})();
}
});
Finally got it to work, in conjunction with Vinicius Souza's answer. Utilizing the $.get() command rather than the ajax(), and activating the timestamp to break the caching of IE.
Thanks Everyone!
(function worker() {
var rand;
$.get("http://somepage/page1/gettrendvars.aspx?timestamp=" + new Date().getTime(), {})
.done(function (data) {
if (totalstrings.length < data.length || data === "") {
if (trendstop === "false") {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
$.get("http://somepage/page1/gettimevars.aspx?timestamp=" + new Date().getTime(), {})
.done(function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
});
})
.fail(function () {
});
setTimeout(worker, 1500);
})();