Delay after each for loop iteration - javascript

In my MVC project, I have passed a list of users to my view, and inside this view I iterate through the list and create an anchor tag for each user. Would it be possible to add a delay after each anchor tag is created? Here is my jquery:
DeskFunction.prototype.init = function() {
var self = this;
var element;
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
for (var i = 0; i < this.allData.length; i++) {
element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + this.allData[i].Name + "' data-name='" + this.allData[i].UserName + "' data-department='" + this.allData[i].DepartmentName + "'></a>");
$(element).css({
"top": this.allData[i].DeskYCoord,
"left": this.allData[i].DeskXCoord
}).appendTo(".map").show('normal').delay(3000);
$(element).on('click', function() {
var user = $(this).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
}
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};
I would like the first tag to be created and added to the map, then a delay of a second, after that the next anchor tag would be added, is this possible? Any help would be appreciated

you can try below code. inside setTimeout write all code that you want to do under the loop. It will get called after 1 sec
for (var i = 0; i < this.allData.length; i++) {
(function(i, self ){
setTimeout(function(){
// ALL LOOP CODE HERE
// use self.allData
}, 1000);
}(i, self ));
}

You could place your code in a setTimeout.
DeskFunction.prototype.init = function() {
var self = this;
var element;
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
for (var i = 0; i < this.allData.length; i++) {
element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + this.allData[i].Name + "' data-name='" + this.allData[i].UserName + "' data-department='" + this.allData[i].DepartmentName + "'></a>");
$(element).css({
"top": this.allData[i].DeskYCoord,
"left": this.allData[i].DeskXCoord
}).appendTo(".map").show('normal');
setTimeout(function(){
$(element).on('click', function() {
var user = $(self).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
}, 3000);
}
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};

With timeouts incrementing and passing all data through a function call to a local scope the following could should do:
for(var i in this.allData) {
// create local function scope saving i and data from being altered by next iterations
(function(i, data) {
setTimeout(function() {
// place your code here, using data (and i)
}, i*1000);
})(i, this.allData[i]);
}
For each element of this.allData this.allData[i] is passed to the local function as data, along with each i. These are used in the inner scope for setting timeouts in intervalls of 1 sec and creating the anchor links.

You actually want an asynchronous loop:
DeskFunction.prototype.init = function() {
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
var self = this,
allData = this.allData,
delay = 1000;
var appendDeleteLink = function appendDeleteLink(i) {
if (i >= allData.length) {
return;
}
var element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + allData[i].Name + "' data-name='" + allData[i].UserName + "' data-department='" + allData[i].DepartmentName + "'></a>");
$(element).css({
"top": allData[i].DeskYCoord,
"left": allData[i].DeskXCoord
}).appendTo(".map").show('normal').delay(3000);
$(element).on('click', function() {
var user = $(this).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
(function(a) {
setTimeout(function() {
appendDeleteLink(a);
}, delay);
})(++i);
};
appendDeleteLink(0);
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};

Related

Removing div based on the ID not existing in a jQuery AJAX response

I am getting rows of content via jQuery AJAX and then populating the table with new content as it is being added. The problem is that some content may be deleted from the database, in which case I also want it removed in real-time from the table.
I suspect I need to loop through the table div IDs and remove any IDs that don't exist in the AJAX response but I'm unsure how to compare them to the data response and then remove them:
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(data) {
var res = data;
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
Any recommendations on how to achieve this?
you are prepending to "records-content" div without clearing it first.
you need to add
$("#records-content tbody").html('')
before starting your for loop.
this way only current data in you database table will populate in table.
Use empty() to clear the records, before prepending new ones.
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(res) {
$("#records-content tbody").empty();
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
To remove elements that are not in the response from server.
Add the following right after success: function(res) {
var currentRows = $("[id^=records-row-]").toArray()
var currentRowsId = currentRows.map(function(row) { return row.id })
var resRows = res.map(function(row) { return "records-row-" + row.id })
var removeRows = currentRowsId.filter(function(rowId) { return resRows.indexOf(rowId) === -1 })
removeRows.forEach(function(rowId) { $("#" + rowId).remove() })
So that it looks like this
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(res) {
var currentRows = $("[id^=records-row-]").toArray()
var currentRowsId = currentRows.map(function(row) { return row.id })
var resRows = res.map(function(row) { return "records-row-" + row.id })
var removeRows = currentRowsId.filter(function(rowId) { return resRows.indexOf(rowId) === -1 })
removeRows.forEach(function(rowId) { $("#" + rowId).remove() })
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
With comments
var currentRows = $("[id^=records-row-]").toArray() // get rows with id starting with "records-row-"
var currentRowsId = currentRows.map(function(row) { return row.id }) // extract ids from rows
var resRowsId = res.map(function(row) { return "records-row-" + row.id }) // extract ids from response that will be added to DOM
var removeRows = currentRowsId.filter(function(rowId) { return resRowsId.indexOf(rowId) === -1 }) // remove every element that is added to DOM and in response from server
removeRows.forEach(function(rowId) { $("#" + rowId).remove() }) // remove elements that are not in response and is added to DOM
Alternative solution
$("#records-content tbody").empty(); to remove every element each time the client fetches new data from server.

Functions are not working in Ajax after a while

I have input which on change should send it is value to ajax and get response back. Ajax is working correct and enters to success,but does not working click function inside it if i do not do changes or click. If i click immediately after response it works, but if i do not do changes in 4-5 seconds it something like close the session. How can i avoid this timing?
here is my example of ajax
$('#unvan_search').on('keyup change', function() {
var unvan = $(this).val();
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
},
error: function(x, t, m) {
alert("error");
}
});
});
This binding here:
$("#unvan_select_div ul").on("click", '.get_street', function() { ... }
There’s no need to declare it in the success callback. This kind of delegate bindings is there for that purpose: being able to handle events on elements created at a later stage
It may work if you structure it like this.
var ret = false;
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
ret = true;
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
return;
},
error: function(x, t, m) {
alert("error");
}
});
});
if(ret) {
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
}

keep the memory of more than one index

I have more than three TextBoxes. I want to send this data as in the code. The "indeks " value is always the last click. How do I keep the index?
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
if (txtvalue != "") {
if (i)
field += " and ";
field = field + "[" + obje[indeks]+ "]" $(this ).val() + "'";
i++;
}
});
});
},
As I wasn't sure if I got your question right, I prefered to comment on your topic - but now it seems that my answer helped you, so I decided to post it as an actual answer:
1st step: declare an array outside your success handler
2nd step: push the index and the value for the element into this array
3rd step: loop through all entries of the array and build your 'select' statement
Here is your edited example:
https://jsfiddle.net/Lk2373h2/1/
var clickedIndexes = [];
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
$(this).attr('id', i);
var txtvalue=$(this).val();
if (i)
clickedIndexes.push({
index: indeks,
value: $(this ).val()
});
var selectString = "";
for (var u = 0; u < clickedIndexes.length; u++) {
selectString += "[" + obje[clickedIndexes[u].index].ALAN + "]" + "=" + "'" + clickedIndexes[u].value + "'";
}
field = selectString;
i++;
});
});
},

use JSON variable in jQuery dynamically

I have two DIVs, #placeholder AND #imageLoad. When the user clicks on a particular thumb its larger version (thumb2) should then appear in #imageLoad DIV.
Here is the jQuery that needs to be fixed:
$.getJSON('jsonFile.json', function(data) {
var output="<ul>";
for (var i in data.items) {
output+="<li><img src=images/items/" + data.items[i].thumb + ".jpg></li>";
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
//This is wrong!! Not working..
$('li').on({
mouseenter: function() {
document.getElementById("imageLoad").innerHTML="<img src=images/items/" +
data.items[i].thumb2 + ".jpg>";
}
});
Here is the external JSON file below (jsonFile.json):
{"items":[
{
"id":"1",
"thumb":"01_sm",
"thumb2":"01_md"
},
{
"id":"2",
"thumb":"02_sm",
"thumb2":"02_md"
}
]}
$.getJSON('jsonFile.json', function(data) {
var output="<ul>";
for (var i = 0; i < data.items.length; i++) {
output += "<li><img thumb2='" + data.items[i].thumb2 + "' src='images/items/" + data.items[i].thumb + ".jpg'></li>";
}
output += "</ul>";
$("#placeholder").html(output);
$('li').on({
mouseenter: function() {
$("#imageLoad").html("<img src='images/items/" + $(this).find('img').attr('thumb2') + ".jpg'>");
}
});
});
Your variable data is declared only within the callback function of your getJSON call and hence it is not available in the other methods/ event handlers. Store it to a global variable when you get it. Like Below:
var globalData;
$.getJSON('jsonFile.json', function(data) {
globalData = data;
var output="<ul>";
for (var i in data.items) {
output+="<li id=\"listItem" + i + "\"><img src=images/items/" + data.items[i].thumb + ".jpg></li>";
}
output+="</ul>";
document.getElementById("placeholder").innerHTML=output;
});
//This is wrong!! Not working..
$('li').on({
mouseenter: function() {
var index = parseInt($(this).attr('id').substring(8));
document.getElementById("imageLoad").innerHTML="<img src=images/items/" +
globalData.items[index].thumb2 + ".jpg>";
}
});
Firstly, $.getJSON is asynchronous, so the binding of mouseenter following the async function will not work as the li elements does not exist when you attach the event handler. Secondly, store the second image source in a data attribute on each li element, and just retrieve that data attribute in the mouseenter function:
$.getJSON('jsonFile.json', function(data) {
var out = $("<ul />");
for (var i in data.items) {
$('<li />', {
src: 'images/items/' + data.items[i].thumb + '.jpg'
}).data('big', data.items[i].thumb2).appendTo(out);
}
$("#placeholder").html(out);
});
$('#placeholder').on('mouseenter', 'li', function() {
var bigImg = $('<img />', {
src: 'images/items/' + $(this).data('big') + '.jpg'
});
$("#imageLoad").html(bigImg);
});​

Changing global variables in a ajax call

I've been trying to get this right for quite some time, I'm trying to append the object from the first ajax call after the second ajax call. But the for loop seems to iterate the changing of the value to the last result before appending the information, having the last post appended every time.
var scribjson =
{
"user_id" : localStorage.viewing,
};
scribjs = JSON.stringify(scribjson);
var scrib = {json:scribjs};
$.ajax({
type: "POST",
url: "getScribbles.php",
data: scrib,
success: function(result)
{
var obj = jQuery.parseJSON(result);
for(var i = 0; i < obj.length; i+=1)
{
var userjson =
{
"user_id" : obj[i].user_id
};
userjs = JSON.stringify(userjson);
var user = {json:userjs};
localStorage.post = obj[i].post;
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
}
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
Since ajax calls It looks like the all success functions of the inner ajax call are being called after the loop has ended, so i will always be the last iterated value.
Try this:
(function(i)
{
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
})(i);
This will create a closure on i, which will give each ajax call its own copy of the current value.
Use an IIFE:
success: (function(i){return function(result) {
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
}})(i),
etc. Currently your loop generated ajax success handlers contain a direct reference to the counter itself, which (by the time they are called) has reached its final value.

Categories