execute javascript after for loop - javascript

I have a for loop that gets data from lists in subsites to build a html list on the page using an async ajax request, this works, but i wish to order the list after it has been generated to show the list in alphabetical order. I am on a learning curve with javascript so any help is appreciated. I need to run the sortProjects function after the onWebsLoaded function is complete.
function onWebsLoaded(sender, args) {
for (var i = 0; i < this.webs.get_count(); i++)
{
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
getProjectProperties(url, title, desc, client, id);
}
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}

You can amend your logic so that you store an array of the promises returned from the $.ajax() calls. You can then apply() that array to $.when and call sortProjects(). Try this:
function onWebsLoaded(sender, args) {
var requests = [];
for (var i = 0; i < this.webs.get_count(); i++) {
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
requests.push(getProjectProperties(url, title, desc, client, id));
}
$.when.apply($, requests).done(sortProjects);
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
// note 'return' below
return $.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}

Related

Active or Inactive on Button click in ASP.Net MVC?

I am getting return json data from server,every value is inserted in table except status.
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
if (item.Status == "Y") {
item.Status = + '<img src="~/img/Active.png" height="32" width="32"/>'
}
else (item.Status == "N")
{
item.Status = + '<img src="~/img/InActive.png" height="32" width="32"/>'
}
var t = i + 1;
var rows = "<tr>"
+ "<td>" + t + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + '' + item.Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
}
if item.Status == "N" means InActive image will display and if item.Status == "Y" means Active image will display
But in my code Status Value i didn't get any idea.?
Controller:
public ActionResult ViewModules(int id)
{
Domain_Bind();
dynamic mymodel = new ExpandoObject();
userType type = new userType();
List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
List<ViewRoleModules> RoleList;
List<ViewRoleModules> role = new List<ViewRoleModules>();
foreach (ViewRoleModules emp in EmpList)
{
RoleList = type.GetSiteRoleModulesViews(emp.ModuleID);
foreach (ViewRoleModules vip in RoleList)
{
role.Add(new ViewRoleModules
{
RoleName = vip.RoleName,
ModuleID = vip.ModuleID
});
}
}
var data = new { EmpList = EmpList, role = role };
return Json(data, JsonRequestBehavior.AllowGet);
}
Your code is a bit of a mess to be honest with several syntax errors. Hope this helps:
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
var roleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
var moduleName = item.ModuleName;
if (item.ParentModuleID == -1) {
moduleName = " -- " + moduleName;
}
var status = '';
if (item.Status == "Y") {
status = '<img src="~/img/Active.png" height="32" width="32"/>';
} else {
status = '<img src="~/img/InActive.png" height="32" width="32"/>';
}
var row = "<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>" + moduleName + "</td>" +
"<td>" + item.Url + "</td>" +
"<td>" + roleName[i].RoleName + "</td>" +
"<td>" + status + "</td>" +
"</tr>";
$('#example tbody').append(row);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});

filter duplicate rows with cake php and java script

I'm trying to filter table which is append using java script with cake php frame work .
and the following code is for adding this tables when i have click on add new magazine ,, but the problem is that , It's add double rows which has been added before . So i need to filter the added rows to delete the duplicated row.
/// function to show magazines data table
$('#add_researches_button').click(function () {
$("input[name='bstock_researchs_id[]']:checked").each(function (i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function (data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function (index, value) {
CountResearches++;
$("#researches").append("<tr><td>"
+ value.research_serial +
"</td><td>"
+ value.research_release_date +
"</td><td>"
+ value.research_release_hejry_date +
"</td><td>"
+ value.research_pages +
"</td><td>"
+ value.research_copies +
"</td></tr>"
);
});
/// function to show magazines data table
$('#add_researches_button').click(function() {
$("input[name='bstock_researchs_id[]']:checked").each(function(i) {
val[i] = $(this).val();
});
$.ajax({
type: "POST",
url: '../BstockIn/getResearchesIds/' + val,
dataType: "json",
success: function(data) {
$('#researches').css('display', 'block');
var res = $.parseJSON(data);
var CountResearches = 0;
jQuery.each(res, function(index, value) {
CountResearches++;
if ($("#researches tr[data-id='" + value.research_serial + "']").length == 0)
$("#researches").append("<tr data-id='" + value.research_serial + "'><td>" +
value.research_serial +
"</td><td>" +
value.research_release_date +
"</td><td>" +
value.research_release_hejry_date +
"</td><td>" +
value.research_pages +
"</td><td>" +
value.research_copies +
"</td></tr>"
);
});

400 bad request while passing object and value to url

I know how to pass data in url in json or with plain parameters but this is something different
see the below image :-
http://www.tiikoni.com/tis/view/?id=23d9b98
My api Url /geniedoc/api/doctor/Search
as we can see one thing is in object and two paramater is simply passing
can you suggest me a ajax call?
my ajax call
function getNewSlotContent(startIndex, totalRows) {
var skipindex = 0;
if (startIndex > 1) {
skipindex = totalRows;
}
var totalrows = totalRows + 10;
var searchByName = document.getElementById("searchByName").value;
var selectedSpeciality = document.getElementById("searchByName").value;
if (selectedSpeciality != null || selectedSpeciality != "") {
selectedSpeciality = encodeURIComponent(selectedSpeciality);
}
$("#preloader").addClass("pageload");
$("#preloader").show();
var dataString = '{"firstName":"'+ searchByName + '","start_index":"' + skipindex + '","rows":"' + totalrows +'"}';
console.log(dataString);
$.ajax({
type: 'POST',
url : '/geniedoc/api/doctor/search',
data: dataString,
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type':'application/json'},
timeout: 100000,
success: function(data) {
var op = "";
for (doctor in data.response.rows) {
op += '<div class="post-sec">';
op += '<img src="/geniedoc/ajax/data/displayImage?fileName=' + data.response.rows[doctor].profilePicId + '" alt="">';
if (data.response.rows[doctor].prefix == null) {
data.response.rows[doctor].prefix = "";
}
op += '<a target="_blank" href="/doctor/' + data.response.rows[doctor].seo_name + '/' + data.response.rows[doctor].idKey + '" class="title"> ' + data.response.rows[doctor].prefix + ' ' + data.response.rows[doctor].firstame + ' ' + data.response.rows[doctor].last_name + '</a>';
op += '<span class="date">' + data.response.rows[doctor].speciality_id + '</span>';
op += '</div>';
op += '<div class="clear"></div>';
}
$("#preloader").hide();
$("#preloader").removeClass("pageload");
$("#doctor-data").html(op);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}
Modify your dataString like this :
var dataString = {
"firstName":searchByName,
"start_index": skipindex,
"rows": totalrows
};

Get Youtube and Vimeo thumbnails using ID on mobile

I am trying to get the thumbnails to display in a list
I have a database where the video name, type (video provider: youtube or vimeo), and video id, but the thumbnails are not displaying at all. I am doing this inside a loop, i.e, writing the HTML doc in a for loop to get the whole list from the database. I did a lot of research but it is still not working. Any idea why?
here is a portion of the code:
if (resp[0].recstatus != "NOTFOUND") {
for (var i = 0; i < resp.length; i++) {
p_str_li += "<li onclick=\"app.frmvideoGalleryService.viewModel.onVListClick('" + resp[i].drill_id + "')\" id='vid1" + i + "' class='videoPreview'>"
p_str_li += " <div id='vid2" + i + "' class='vid_thumb'>"
p_str_li += " <a id='vid3" + i + "' >"
p_str_li += " <img id='vid4" + i + "' src='styles/images/placeholders/thumbnail.jpg' alt='commentPic'>"
if (resp[i].video_type == 'VIMEO') {
$.ajax({
type: 'GET',
url: 'http://vimeo.com/api/v2/video/' + resp[i].video_id + '.json',
async: true,
jsonp: 'callback',
dataType: 'jsonp',
success: function (data) {
thumbnail_src = data[0].thumbnail_medium;
$('#vid4' + i).attr('src', thumbnail_src);
}
});
}
else if (resp[i].video_type == 'YOUTUBE') {
var thumbnail_src = 'http://i2.ytimg.com/vi/' + resp[i].video_id + '/hqdefault.jpg';
$('#vid4' + i).attr('src', thumbnail_src);
}
else {
$('#vid4' + i).attr('src', 'styles/images/placeholders/thumbnail.jpg');
}
p_str_li += " </a>"
p_str_li += " </div>"
}
}
Check these solutions:
Youtube: http://salman-w.blogspot.it/2010/01/retrieve-youtube-video-title.html
Vimeo: Dynamically get thumbnails and titles of vimeo videos [SOLVED!]

How to set CRUD working in Kendo?

How to set CRUD working in Kendo? Update and read is ok, but create not. This is my code for this part:
create: {
url: function (data) {
return $("#gatewayPath").data("value") + "odata/ods/ProcessProductionPerformanceMovements";
},
dataType: "json",
type: "POST",
beforeSend: function (x) {
var auth = $("#authenticationType").data("value") + " " + $("#authenticationToken").data("value");
x.setRequestHeader("Authorization", auth);
}
},
and in parameterMap I have:
if (operation === "create") {
return '{ "_Key": "' + data._Key +
'", "Comment": "' + data.Comment +
'","MovementType": "' + data.MovementType +
((data.Unit) ? '","_UnitKey": "' + data.Unit._Key: "") +
((data.Material) ? '","_MaterialKey": "' + data.Material._Key: "") +
'","MaterialLotID": "' + data.MaterialLotID +
'","Status": "' + data.Status +
'","Quantity": "' + data.Quantity +
'","Description": "' + data.Description +
'","_UnitKey": "' + data._UnitKey +
'","_ProdPerfHeaderKey": "' + data._ProdPerfHeaderKey +
'","StockType": "' + data.StockType +
'","StockIndicator": "' + data.StockIndicator +
'","SAPStorageLocation": "' + data.SAPStorageLocation +
'"}';
}
There is a create example here on telerik.com.
var dataSource = new kendo.data.DataSource({
transport: {
/* the other CRUD settings are ommitted for brevity */
create: function (e) {
// batch is disabled
// generate appropriate data item ID and save the new items to the original datasource
e.data.my_ID_field_name = 123;
// ...
// on success return the new data items with IDs
e.success(e.data);
// on failure
//e.error("XHR response", "status code", "error message");
}
} });

Categories

Resources