Pausing for loop after every execution - javascript

i have a page, wherein i am using a ajax for inserting records... now in javascript i am using a for each loop to loop the html table and insert the rows in database. but happens is as foreach loop executes fast, it sometime, does not insert some records.. so i want to make the loop sleep for sometime once it has executed first and thereafter...
is there any way to pause the for loop.. i used setTImeout.. but it just delay it first time and not consecutive times...
here's my code.
function AddTopStories() {
$("#tBodySecond tr").each(function (index) {
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", this).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
window.setTimeout(showSuccessToast(data.d), 3000);
},
error: function (data) {
window.setTimeout(showSuccessToast("Error:" + data.reponseText), 3000);
}
});
});
}
Please help me to resolve this issue... its utmost important.
*************************************UPDATED CODE AS PER THE CHANGES BY jfriend00*********
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex > stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
alert($("td:nth-child(1)", item).text());
addNext();
}
}
This just does not do anything... does not alert...

I'd recommend you break it into a function that does one story and then you initiate the next story from the success handler of the first like this:
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex >= stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", item).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
addNext(); // upon success, do the next story
showSuccessToast(data.d);
},
error: function (data) {
showSuccessToast("Error:" + data.reponseText);
}
});
}
addNext();
}

Ugly, but you can fake a javascript 'sleep' using one of the methods on this website:
http://www.devcheater.com/

Related

While loop wont print twice

Currently I'm trying to print two copies of the same receipt without using the browser-print dialogue. Now unfortunately there is no way to pass the number of copies to the print dialog so the only solution I came up with is doing it in a LOOP, but when looping the print command it does not work! while looping the whole POST method works just fine.
Here's the code before I enter the loop
print function
function p_print(receipt) {
$('#receipt_section').html(receipt.html_content);
__currency_convert_recursively($('#receipt_section'));
__print_receipt('receipt_section');
}
Code without Loop
$.ajax({
method: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(result) {
if (result.success == 1) {
if (result.mail_enabled) {
window.open(result.mail_enabled);
}
$('#modal_payment').modal('hide');
toastr.success(result.msg);
//Check if enabled or not
if (result.receipt.is_enabled) {
p_print(result.receipt);
}
} else {
toastr.error(result.msg);
}
},
});
Functioning loop that prints twice but also POSTS the data twice
var Count = 0;
var Copies = 2;
while ( Count < Copies ) {
$.ajax({
method: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(result) {
if (result.success == 1) {
if (result.mail_enabled) {
window.open(result.mail_enabled);
}
$('#modal_pay').modal('hide');
toastr.success(result.msg);
if (result.receipt.is_enabled) {
p_print(result.receipt);
}
} else {
toastr.error(result.msg);
}
},
});
Count ++;
};
Now If I apply the loop only on p_print(result.receipt) it wont print twice, only by applying it to the whole POST request it would then print twice but also stores the data twice which is not a proper solution at all.
Any help would be very appreciated.

Populate Ajax response with clickable elements that fires another Ajax with correct parameters

So i have a function running an Ajax call that receives data and populate that as a table.
The response contains some rows with data and i now want to add a small fontawsome icon that when clicked fires another function with a parameter.
So i have this:
var latestprecasedata = '';
function getPreCaseData() {
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/GetPreCase",
dataType: "json",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
data = $.parseJSON(data);
$("#PreCaseTblBody").html("");
for (var i in data) {
$("#PreCaseTblBody").append("<tr><td>" + data[i].pSubject + "</td><td><span class='preplus' id='" + data[i].pID + "'><i class='fa fa-plus'></i></span></td><td>-</td></tr>");
}
if (latestprecasedata !== response.d) {
$("#precasestatus").removeClass("titleupd1").addClass("titleupd2");
latestprecasedata = response.d;
}
else {
$("#precasestatus").removeClass("titleupd2").addClass("titleupd1");
}
}
$("#PreCaseTblBody tr:odd").css('background-color', '#f9f9f9'); //
$("#PreCaseTblBody tr:even").css('background-color', '#f1ffee');
setTimeout(getPreCaseData, 10000);
}
});
}
This works and every 10 seconds data is repopulated. (Maybe not the fastest solution, but it works..)
As you all can se i have a span with class=preplus and id of a unique value coming from my Ajax response. When inspecting the page i can see that every row from my Ajax response have a unique id.
For example two row looks like this:
<tr><td>Cables</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
<tr><td>Skrews</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
So now i have the data populated with span containing a unique id that i want to pass to another function.
I've tried span, div, buttons but the only one time I actually got a event fire was when i placed my second function inside the
for (var i in data) {
... and i know, that's not right at all because all rows contained the last id obviously...
So my other function resides outside my first function and look like this (I've tried many different methods to get the id of my span but for now, I'm here)
$(".preplus").click(function () {
var qID = $(this).attr('id');
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/UpdateQ",
dataType: "json",
data: "{'qid':'" + qID + "','pm':'plus'}",
success: function (data) {
}
});
return false;
});
Please guide me.

How to stop setInterval in a do while loop in jquery

I want to do is stop setInterval after the do while loop meet the condition.
My problem is even the while loop condition is meet the setInterval is still running.
do
{
setInterval(
Vinformation();
,500);
}while($('#emailCodeResult').val() !='')
function Vinformation(){
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
}
});
return false;
}
You don't need while loop here at all. In combination with setInterval it doesn't make sense. What you need is probably just setInterval:
var interval = setInterval(Vinformation, 500);
function Vinformation() {
if ($('#emailCodeResult').val() == '') {
clearInterval(interval);
return;
}
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType: "JSON",
success: function (result) {
}
});
}
Use clearInterval function to stop interval.
Also note, that setInterval expects function reference as the first argument so this setInterval(Vinformation(), 500) is not correct, because you immediately invoke the Vinformation function.
var itvl1= window.setInterval(function(){
Vinformation();
},500);
function Vinformation(){
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
if(data.emailCodeResult !=''){
window.clearInterval(itvl1);
};
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType:"Jenter code hereSON",
success: function (result) {
}
});
return false;
}

How to check json response taken longer than 5 seconds?

Below is the sample code of my function. in the for loop one by one product id is pass in the ajax function and get product price from the php file as response and write it and html.
for(var i=0; i < data.products.length; i++){
var doc = data.products[i];
$.ajax({ // ajax call starts
url: 'product.php',
data: { product_id: doc.id },
dataType: 'json',
success: function(data)
{
document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
}
});
}
I have found that sometimes it takes a more time for price to display. i want to check which record is taking time to load. how can check to detect when it takes longer than 5 seconds for the price to load?
Something like this....
var ajaxTime= new Date().getTime();
$.ajax({
type: "POST",
url: "some.php",
}).done(function () {
var totalTime = new Date().getTime()-ajaxTime;
// Here I want to get the how long it took to load some.php and use it further
});
Also, by the way, if you want to prevent sending (i+1) request, before (i) is completed, you'd maybe want to use syncronous ajax request instead of async.
Try to log timestamp beforesend and success or error
$.ajax({ // ajax call starts
url: 'product.php',
data: { product_id: doc.id },
dataType: 'json',
beforeSend: function() {
console.log(new Date().getSeconds());
}
success: function(data)
{
console.log(new Date().getSeconds());
document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
}
});
Use setTimeout, like this:
var timeoutTimer = setTimeout(function() {
// time out!!!.
}, 5000);
$.ajax({ // ajax call starts
url : 'product.php',
data : {
product_id : doc.id
},
dataType : 'json',
success : function(data) {
document.getElementById('price_price' + data.product_id + '').innerHTML = data.products_price;
},
complete : function() {
//it's back
clearTimeout(timeoutTimer);
}
});

Javascript/jquery iterate async problems

I would like to iterate through a certain amount of pages, and populate them with content using ajax calls. The problem is, when I put the ajax calls inside the iteration function it has problems with the synchronous nature of javascript. The iteration has already continued before the ajax call is completed. So I made a workaround where I made the ajax call in a setTimeout, which works fine. But I don't really like this method, and was wondering if there is an alternative (better) solution. (I know that jQuery provides a async: true option, however that did not work)
function populatePages(i) {
pageId = PageIds[i];
containerId = pageIdContainer[i];
$j.ajax({
type: 'GET',
dataType: 'html',
url: url,
data: { pageid: pageId, containerid: containerId },
success: function(data) {
//populate the DIV
}
});
}
i = 0;
x = 50;
$j.each(pagesIds, function(){
setTimeout("populatePages("+i+")", x);
x = x + 50;
i++;
});
Try this (not tested)
function populatePages(i) {
console.log('populatePages', i)
pageId = PageIds[i];
return $.ajax({
type: 'GET',
dataType: 'html',
url: '/echo/html',
data: { pageid: pageId},
success: function(data) {
}
});
}
function messy(index){
console.log('messy', index)
if(index >= PageIds.length){
return;
}
populatePages(index).always(function(){
console.log('complete', index)
setTimeout(function(){
messy(index + 1)
});//to prevent possible stackoverflow
})
}
PoC: Fiddle

Categories

Resources