javascript function inside loop run only once - javascript

I have a javascript function which is looping on my data basically I call another function inside of loop but it only execute once on last index here is my code and this function I wants to execute on every time.
basically inside loop I call ajax that is run fine on each index of loop but issue is to call db.transaction function which is only execute on last index
db.transaction(populateDB, errorCB);
function renderList(tx, results) {
len = results.rows.length;
console.log("rows" + results.rows.length);
for (var i = 0; i < len; i++) {
(function (i) {
var nid = results.rows.item(i).nId;
$.ajax({
type: 'post',
url: 'http://localhost:50972/LibraryService.asmx/GetTitleSections',
dataType: 'json',
data: "{'MainSectionId':'" + nid + "'}",
contentType: 'application/json; charset=utf-8',
async: false ,
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
},
error: function (error) {
console.log(error);
}
});
db.transaction(TblTitleSection, errorCB);
})
(i);
// htmlstring += '<li>' + results.rows.item(i).strTitle + '</li>';
// $('#resultList').append("<li>" + results.rows.item(i).strTitle + "</li>");
$('#'+i).append( results.rows.item(i).strTitle );
// $('#tblMainSection').append("<tr><td>" + results.rows.item(i).strTitle + "</td></tr>");
}
// $('#resultList').html(htmlstring);
}

Perhaps you loop continues while running your ajax call. You could try putting the increment (i++) in your success function to force the loop to halt till the function is finished. Syntax seems to be okay.
replace:
for (var i = 0; i < len; i++) {
With:
for (var i = 0; i < len;){
And
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
}
With:
success: function (response) {
var data = response.d;
alert(data.nId);
TitleSectionData = data;
i++;
}
See if that works :)

Related

button function is not defined with htmlstring

I am able to display out all the details including the button. However, the main problem is that the when I click the button, nothing happens. It says that BtnRemoveAdmin() is not defined when I inspect for errors. However, I have function BtnRemoveAdmin()?? I have tried to move the function to htmlstring. Nothing works. I am not sure what went wrong.
(function () {
$(document).ready(function () {
showadmin();
});
function showadmin() {
var url = serverURL() + "/showadmin.php";
var userid = "userid";
var employeename = "employeename";
var role ="role";
var JSONObject = {
"userid": userid,
"employeename": employeename,
"role": role,
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getAdminResult(arr);
},
error: function () {
alert("fail");
}
});
}
function _getAdminResult(arr) {
for (var i = 0; i < arr.length; i++) {
htmlstring = '<div class="grid-container">' +
'<div>' + arr[i].userid + '</div>' +
'<div>' + arr[i].employeename + '</div>' +
'<div>' + arr[i].role + '</div>' +
'<div>' + '<button onclick="BtnRemoveAdmin()">Remove</button>' + // 'BtnRemoveAdmin' is not defined
'</div>' ;
$("#name").append(htmlstring);
}
function BtnRemoveAdmin() {
var data = event.data;
removeadmin(data.id);
}
}
function removeadmin(userid) {
window.location = "removeadmin.php?userid=" + userid;
}
})();
All your code is defined inside an IIFE.
That includes BtnRemoveAdmin.
When you generate your JavaScript as a string, it is evaled in a different scope.
BtnRemoveAdmin does not exist in that scope.
Don't generate your HTML by mashing strings together.
Use DOM instead.
function _getAdminResult(arr) {
var gridcontainers = [];
for (var i = 0; i < arr.length; i++) {
var gridcontainer = $("<div />").addClass("grid-container");
gridcontainer.append($("<div />").text(arr[i].userid));
gridcontainer.append($("<div />").text(arr[i].employeename));
gridcontainer.append($("<div />").text(arr[i].role));
gridcontainer.append($("<div />").append(
$("<button />")
.on("click", BtnRemoveAdmin)
.text("Remove")
));
gridcontainers.push(gridcontainer);
}
$("#name").append(gridcontainers);
}
I use JQuery, and sometimes I get the same problem with plain JS functions not being called.
So I create JQuery functions :
$.fn.extend({
btnRemoveAdmin: function() {
...//Do what you want here
}
});
To call it use :
<button onclick="$().btnRemoveAdmin();"></button>
Hope it helps you !

Call second function after first function fully completed in java script

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.

request.getParameter("pgIndex") always returns null in the servlet

I am trying to paginate rows of a table inside my servlet using hibernate.But once I click on the desire index of the page it always gives me only the first set of row of the table.So I put System.out.print() at every major sections and finally found out that the request.getParameter("pgIndex") is always returns null.
My servlet code:
int pageIndex = 0;
int totalNumberOfRecords = 0;
int numberOfRecordsPerPage = 5;
String sPageIndex = request.getParameter("pgIndex");
//whether pgIndex=1 or pgIndex=2 in the url, always returns null as the output.
System.out.println("pg - " + sPageIndex);
pageIndex = sPageIndex == null ? 1 : Integer.parseInt(sPageIndex);
int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;
List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class)
.setFirstResult(s)
.setMaxResults(numberOfRecordsPerPage)
.list();
for (ProductHasSize pro : phs) {... some html content here...}
Criteria criteriaCount = ses.createCriteria(ProductHasSize.class);
criteriaCount.setProjection(Projections.rowCount());
totalNumberOfRecords = (int) (long) (Long) criteriaCount.uniqueResult();
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
for (int j = 1; j <= noOfPages; j++) {
String myurl = "products.jsp?pgIndex=" + j;
String active = j == pageIndex ? "active" : "";
s2 = s2 + "<li class='" + active + "'>" + j + "</li>";
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"d1\":\"" + s1 + "\",\"d2\":\"" + s2 + "\"}]");
products.jsp
<div class="row">
<div class="col-md-12">
<ul class="pagination" id="pagId"></ul>
</div>
</div>
JavaScript
$(document).ready(function () {
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
UPDATE :
$(document).on("click", "#pagId a", function (event) {
//tried with adding another function . But still returns null.
event.preventDefault();
var para = $(this).attr('href').match(/\d+/);
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
data: {pgIndex: para},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
Thanks in advance.
In sending JSON data, you will not simply receive it as request parameter. Instead, just add "normal" parameter:
Sending as HTTP POST
$.ajax({
url: 'AdimnProductFilterAction',
type: 'POST',
data: {
'pgIndex': para
},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
Or as HTTP GET
$.ajax({
url: 'AdimnProductFilterAction?pgIndex='+para,
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
To add parameter into your servlet call.

Parse First Title from RSS with jQuery

I don't want to parse all title from the list. I only want the first title to be parsed. Any suggestion?
function parseRSS(url, container) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
$.each(data.responseData.feed.entries, function(key, value){
var thehtml = '<h3>'+capitaliseFeed(value.title)+'</h3>';
$(container).append(thehtml);
});
}
});
}
function capitaliseFeed(string) {
return string.toUpperCase();
}
Instead of $.each you could loop the data and keep only the first entry
for (var i = 0; i < data.responseData.feed.entries.length; i++) {
var entry = data.responseData.feed.entries[i];
var thehtml = '<h3>'+capitaliseFeed(entry.title)+'</h3>';
$(container).append(thehtml);
break;
}

Ajax get data to get another ajax data

I need some pointer about combining nested ajax call.
$.ajax({
type: "GET",
dataType: "json",
url: generalurl + "/Chore" + objectid + "?$expand=Process",
success: function (data, textStatus) {
list = $(data)[0]["TM1.ChoreProcessRel"];
res = [];
for (var i = 0, l = list.length; i < l; i++) {
var e = list[i];
GetDirectories(e.ID, function (d) {
alert(d); //this is working fine already
});
//I just want to include d on the below statement but I'm still getting undefined
res.push({
title: "" + e.Name, key: e.LogicalName + d,
});
}
}
});
and this is the GetDirectory code
function GetDirectories(choreid, callback) {
var theurl = webapiurl + '/Models' + getTopUrlVars()["model"] + '/ChoreProcess(' + choreid + ')?$expand=Process';
$.ajax({
type: "GET",
url: theurl,
data: {},
dataType: "json",
success: function (response) {
callback(response["TM1.ChoreProcessesProcess"][0].ID);
},
failure: function (msg) {
alert(msg);
}
});
}
Is it possible to do this? I tried using global variable but then the first value is "".
if you have return in getDirectories, try use variable
var d = GetDirectories(e.ID, function (d) {
alert(d); //this is working fine already
});
//I just want to include d on the below statement but I'm still getting undefined
res.push({
title: "" + e.Name, key: e.LogicalName + d,
});

Categories

Resources