Break the for loop based on the ajax success variable - javascript

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

Related

i want next ajax request wait until the previous request is done

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

Get property to array and write it to new array (JS)

I have code to get data from google api.
Here is the code:
$.ajax({
url: dburl,
dataType: 'json',
async: false,
type: 'GET',
data: model,
success: function (data) {
if (data.length !== 0) {
speeddata = data;
for (var i = 0; i < speeddata.length; i++) {
path = "path=" + speeddata[i].Latitude2 + ',' + speeddata[i].Longitude2;
var googleurl = "https://roads.googleapis.com/v1/speedLimits?"
+ path + "&key=" + roadsapikey;
$.ajax({
url: googleurl,
dataType: 'json',
async: false,
type: 'GET',
success: function(data) {
speedlimits = data;
console.log(speedlimits);
for (var i = 0; i < speedlimits.length; i++) {
speedobject.push({
speedlimits: speedlimits[i].speedLimits.speedLimit
});
}
console.log(speedobject);
}
});
}
}
},
error: function () {
alert("Error");
}
});
Here is what I get in response here - speedlimits
Response
I try to take speedLimit property and push it to new object.
Like this:
for (var i = 0; i < speedlimits.length; i++) {
speedobject.push({
speedlimits: speedlimits[i].speedLimits.speedLimit
});
}
But when I show speedobject in console it is empty.
Why so? Where is my problem?
The speedlimits object looks like this:
speedlimits = { // You're looping over this (speedlimits)
speedLimits: [ // You should be looping over this (speedlimits.speedLimits[i])
{speedLimit: 50},
// ...
],
snappedPoints: []
}
You are trying to loop over the speedLimits and snappedPoints items - not the elements within speedLimits.
for (var i = 0; i < speedlimits.speedLimits.length; i++) {
speedobject.push({
speedlimits: speedlimits.speedLimits[i].speedLimit
});
}
according to the data example here the api returns an object, not an array.. so your success function would look like this.. Make sure you get the case right too.
success: function(data) {
speedlimits = data.speedLimits;
console.log(speedlimits);
for (var i = 0; i < speedlimits.length; i++) {
speedobject.push({
speedlimits: speedlimits[i].speedLimit
});
}
console.log(speedobject);
}

Update textarea after get response from servlet in javascript

I have a program which calls a function in javascript with 1 o more requests to 1 servlet, I want to execute request after request and get the response after each exucution, to make this I have 1 function, but it only shows the result after all requests have been executed.
function cmd(args) {
width = 0;
var res = args.split('\n');
var largo = res.length;
var progressLength = 100 / largo;
for (var i = 0; i < largo; i++)
{
if (res[i] == 'desconectar')
{
desconectar();
break;
}
else
{
executeCMD(res[i]);
}
}
}
function executeCMD(args)
{
$.ajax({
type: "POST",
url: 'Controlador',
data: {cmd: args, operacion: 1},
success: function (response) {
document.getElementById('respuesta').value = document.getElementById('respuesta').value + response;
},
dataType: 'text',
async: false
});
}
If I add window.alert(response); inside success field it shows the progress step by step and works fine, but it show alerts which I don't want.
This is I want http://imgur.com/a/9nclR but I'm getting only last picture.
The solution if anyone is intersting was using a recursive function as next:
function cmd(args) {
width = 0;
move(0);
var res = args.split('\n');
var largo = res.length;
var valInit = 0;
if (largo > valInit)
{
executeCMD(res, valInit);
}
}
function executeCMD(args, i)
{
$(document).ready(function () {
$.ajax({
type: "POST",
url: 'ControladorServlet',
data: {cmd: args[i], operacion: 1, ticket: ticket, iddispositivo: sesion},
success: function (response) {
var textarea = document.getElementById('respuesta');
var res = response.trim().split('\n');
if(error){//dc}
else
{
document.getElementById('respuesta').value = document.getElementById('respuesta').value + response.trim() + "\n\n";
var valor = (100) * (i + 1) / args.length;
move(valor);
if (i + 1 < args.length)
{
executeCMD(args, i + 1);
}
}
},
dataType: 'text'
});
});
}

Can ghost.py scrape a web page with javascript setInterval update repeatedly?

I plan to use Ghost.py to scrape a web page which is updated every 5 seconds by setInterval.
How can I scrape the updated data by Ghost.py repeatedly, once there is a new update by this script?
The setInterval code below:
(function () {
var template;
(function () {
template = $("#template1 tbody").html();
GetData();
})();
function GetData() {
var max = 100,
sn = $.data(document, "sn");
if (sn === undefined) {
sn = 0;
} else {
sn = parseInt(sn, 10);
}
$.ajax({
url: path + "ashx/notice.ashx",
async: true,
cache: false,
data: {
act: "GetBotSignal",
sn: sn,
max: max
},
type: "get",
dataType: "json",
success: function (data) {
if (data !== null && data.length !== 0) {
var html = "";
var expselbox = $(".exp-sel-box");
for (var i = 0, j = data.length; i < j; i++) {
var item = template;
item = item.replace(/\{0}/g, data[i].SignalOccurTime);
(parseFloat(data[i].Ratio) >= 2 && parseFloat(data[i].Probability) >= 50) ? " sp" : "");
html += item;
}
expselbox.prepend("<tr ef=\"1\" style=\"height:0px;\"></tr>");
expselbox.find("tr[ef=1]").animate({ "height": (34 * data.length) + "px" }, "fast", function () {
expselbox.find("tr[ef='1']").remove();
expselbox.prepend(html);
expselbox.find("tr:hidden").fadeIn("fast");
expselbox.find("tr:gt(" + max + ")").remove();
$.data(document, "sn", data[0].SN);
ScrollBar($(".expscall-out"), 642, 342, true);
});
}
}
});
}
if (srvTime.getHours() > 7 && srvTime.getHours() < 14) {
setInterval(function () {
GetData();
}, 5000);
}
})();

How to return what I want from ajax asynchronous request?

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?

Categories