Correctly Updating Div using Javascript and split - javascript

This is a mvc 3 razor vb.net application... I have the code behind doing everything fine so I decided to add a little more to the data coming in to the java so that the screen could be a little more informative about it's current progress... The string that getstatus has coming in is a string delimited with "/" where data.split("/")(0) = the integer in the function and data.split("/")(1) = the string to display in the currentEmail div... This is not working and it is simply because I am a total noob to javascript and i know it is possible..
#Code
ViewData("Title") = "MassEmailSendingStatus"
TempData.Add("emList", TempData("emailaddresses"))
Dim x As String = Guid.NewGuid().ToString
end Code
<div>
Start Process
</div>
<br />
<div id="currentEmail">
</div>
<div id="statusBorder">
<div id="statusFill">
</div>
</div>
<script type="text/javascript">
var uniqueId = '#x';
var tdata = '#TempData("emailaddresses")';
$(document).ready(function (event) {
$('#startProcess').click(function () {
$.post("MassEmailSendingStatus", { id: uniqueId }, function () {
$('#statusBorder').show();
getStatus();
});
event.preventDefault;
});
});
function getStatus() {
var url = 'GetCurrentProgress/' + uniqueId;
$.get(url, function (data) {
var str = data;
var n1 = str.split("/");
var v1 = integer.parseint(n1[0]);
var v2 = n1[1];
if (v1 != "100") {
$('#status').html(data);
$('#currentEmail').html(v2);
$('#statusFill').width(v1);
window.setTimeout("getStatus()", 100);
}
else {
$('#status').html("Done");
$('#statusBorder').hide();
alert("The Long process has finished");
};
});
}
</script>

Found it on my own with some browser lvl debugging..
var v1 = integer.parseint(n1[0]); is wrong it should be var v1 = ParseInt(n1[0]); case sensitive languages = not for noobs like meh.
function getStatus() {
var url = 'GetCurrentProgress/' + uniqueId;
$.get(url, function (data) {
var str = data;
var n1 = str.split("/");
var v1 = integer.parseint(n1[0]);
var v2 = n1[1];
if (v1 != "100") {
$('#status').html(data);
$('#currentEmail').html(v2);
$('#statusFill').width(v1);
window.setTimeout("getStatus()", 100);
}
else {
$('#status').html("Done");
$('#statusBorder').hide();
alert("The Long process has finished");
};
});
}

Related

JavaScript Web Resource issue: getGrid() suddenly started failing

I have a few different JavaScript web resources that use the getGrid(), all of which started failing this week after I enabled the 2020 Wave 1 Updates in D365. The error message shows:
"Error occurred :TypeError: Unable to get property 'getGrid' of undefined or null reference"
Here is my code:
function GetTotalResourceCount(executionContext) {
console.log("function started");
var execContext = executionContext;
var formContext = executionContext.getFormContext();
var resourceyescount = 0;
try {
var gridCtx = formContext._gridControl;
var grid = gridCtx.getGrid();
var allRows = grid.getRows();
var duplicatesFound = 0;
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
var thisRow = row.getData().entity;
var thisRowId = thisRow.getId();
var thisResource = "";
var thisResourceName = "";
var thisResourceID = "";
console.log("this row id=" + thisRowId);
var thisAttributeColl = row.getData().entity.attributes;
thisAttributeColl.forEach(function (thisAttribute, attrIndex) {
var msg = "";
if (thisAttribute.getName() == "new_resource") {
thisResource = thisAttribute.getValue();
thisResourceID = thisResource[0].id;
thisResourceName = thisResource[0].name;
console.log("this resource name=" + thisResourceName)
}
});
var allRows2 = formContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows2.forEach(function (row, rowIndex) {
var thatRow = row.getData().entity;
var thatRowId = thatRow.getId();
var thatAttributeColl = row.getData().entity.attributes;
var thatResource = "";
var thatResourceName = "";
var thatResourceID = "";
thatAttributeColl.forEach(function (thatAttribute, attrIndex) {
if (thatAttribute.getName() == "new_resource") {
thatResource = thatAttribute.getValue();
thatResourceID = thatResource[0].id;
thatResourceName = thatResource[0].name;
if (thatResourceID == thisResourceID && thatRowId != thisRowId) {
duplicatesFound++;
var msg = "Duplicate resource " + thatResource;
console.log("duplicates found= " + duplicatesFound);
}
}
});
});
});
if (duplicatesFound > 0) {
console.log("duplicate found");
Xrm.Page.getAttribute("new_showduplicateerror").setValue(true);
Xrm.Page.getControl("new_showduplicateerror").setVisible(true);
Xrm.Page.getControl("new_showduplicateerror").setNotification("A duplicate resource was found. Please remove this before saving.");
} else {
Xrm.Page.getAttribute("new_showduplicateerror").setValue(false);
Xrm.Page.getControl("new_showduplicateerror").setVisible(false);
Xrm.Page.getControl("new_showduplicateerror").clearNotification();
}
} catch (err) {
console.log('Error occurred :' + err)
}
}
Here is a separate web resource that triggers the function:
function TriggerSalesQDResourceCount(executionContext){
var formContext = executionContext.getFormContext();
formContext.getControl("s_qd").addOnLoad(GetTotalResourceCount);
}
Any ideas how I can fix this? Is this a known issue with the new D365 wave 1 update?
Thanks!
This is the problem with unsupported (undocumented) code usage, which will break in future updates.
Unsupported:
var gridCtx = formContext._gridControl;
You have to switch to these supported methods.
function doSomething(executionContext) {
var formContext = executionContext.getFormContext(); // get the form Context
var gridContext = formContext.getControl("Contacts"); // get the grid context
// Perform operations on the subgrid
var grid = gridContext.getGrid();
}
References:
Client API grid context
Grid (Client API reference)

Javascript trim whitespace on click

I have an email form field. On click, it executes this javascript ...
$(document).on('click', '#add_delegate', function() {
RegistrationHelper.added_delegate = true;
// var button = $(event.target);
var button = $(this);
var uri = button.data('url');
if (typeof uri === 'undefined') {
return false;
}
var input = $('#email_search');
var data = {email:input.val()};
data.text().replace(/ /g,'');
var spinner = $('#delegate_add_spinner');
spinner.css({display:'inline-block'});
$.ajax({type:'POST', url: uri, data:data}).success(function(card) {
var html = $(card);
var data_id = html.attr('data-id');
var existing_elem = $('.mini_addresscard[data-id=' + data_id + ']');
if (existing_elem.length < 1) {
input.popover('hide');
// this is in a seperate timeout because IE8 is so damn stupid; it crashes if run directly
setTimeout(function () {
$('#address_cards').append(html);
var last_card = $('#address_cards div.mini_addresscard').last();
//last_card.get(0).innerHTML = card;
// html.attr("id", 'sdklfjaklsdjf');
last_card.css({display:'none'}).show('blind');
}, 10);
} else {
var background = existing_elem.css('background');
existing_elem.css({'background':'#FFFFAC'});
existing_elem.animate({
'background-color':'#EBEDF1'
}, {
complete: function() {
existing_elem.css({background:background});
}
});
// var border_color = existing_elem.css('border-color');
// existing_elem.css({'border-color':'#EFF038'});
// existing_elem.animate({'border-color':border_color});
}
}).complete(function(data) {
spinner.hide();
}).error(function(data) {
var input = $('#email_search');
input.popover("destroy");
var error = 'Please try again later'; //incase something crazy happens
if(data.status == "422"){
error = 'You cannot add yourself as a supervisor.';
}
if(data.status == "404" ){
error = 'Could not find anyone with that email address.';
}
add_popover(input, error);
input.popover('show');
});
return false;
});
My goal is to trim the whitespace before the AJAX request
So as you can see in the code above I added the line
data.text().replace(/ /g,'');
... but now it renders that button useless. In other words the button does nothing when clicked.
Since you're using jQuery, why not make use of .trim():
This:
var data = {email:input.val()};
data.text().replace(/ /g,'');
Becomes:
var data = {email:$.trim(input.val())};
The trim supposed to remove the spaces at beginning and end of the input:
var input = $('#email_search').val();
input = input.replace(/^\s+/, '').replace(/\s+$/, '');

Get Navigation Term using javascript

Has anyone tried to use Javascript API to get Navigation Term in Sharepoint? I found the code in MSDN but did not have any clue to use it.
http://msdn.microsoft.com/en-us/library/office/jj994618(v=office.15).aspx
Could you please to tell me how I can get current page Navigation Term or get Navigation Term by id using javascript?
Thanks.
You could utilize SP.Publishing.Navigation.NavigationTermSet.getAsResolvedByWeb Method to retrieve Navigation Term Set object. The following example demonstrates how to retrieve Navigation Term Set object and find Navigation Term:
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
SP.SOD.executeFunc('sp.taxonomy.js', 'SP.Taxonomy.TaxonomySession', function () {
SP.SOD.registerSod('sp.publishing.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.publishing.js'));
SP.SOD.executeFunc('sp.publishing.js', 'SP.Publishing.Navigation.NavigationTermSet', function () {
var navTermSetId = 'ccef718f-fc01-4d27-b877-431f2e4bf136';
var navTermId = '1b04f1b2-f5f4-4c7b-a87f-28fb8665824b';
loadNavigationTermSet(navTermSetId,
function(navTermSet){
for(var i = 0;i < navTermSet.get_terms().get_count();i++) {
var navTerm = navTermSet.get_terms().getItemAtIndex(i);
if(navTerm.get_id().toString() == navTermId){
console.log(navTerm.get_taxonomyName());
}
}
},
function(sender, args)
{
console.log('Request failed ' + args.get_message() + ':'+ args.get_stackTrace());
}
);
});
});
});
where
function loadNavigationTermSet(navTermSetId,success,error)
{
var ctx = SP.ClientContext.get_current();
var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);
var termStore = taxonomySession.getDefaultSiteCollectionTermStore(); //retrieve default Term Store
var termSet = termStore.getTermSet(navTermSetId);
var navTermSet = SP.Publishing.Navigation.NavigationTermSet.getAsResolvedByWeb(ctx,termSet, ctx.get_web(), "GlobalNavigationTaxonomyProvider");
ctx.load(navTermSet,'Terms');
ctx.executeQueryAsync(function(){
success(navTermSet);
},
error);
}
Example 2
The following example demonstrates how to retrieve Navigation Terms:
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
SP.SOD.executeFunc('sp.taxonomy.js', 'SP.Taxonomy.TaxonomySession', function () {
SP.SOD.registerSod('sp.publishing.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.publishing.js'));
SP.SOD.executeFunc('sp.publishing.js', 'SP.Publishing.Navigation.NavigationTermSet', function () {
var navTermSetId = 'ccef718f-fc01-4d27-b877-431f2e4bf136';
loadNavigationTerms(navTermSetId,
function(navTerms){
for(var i = 0;i < navTerms.get_count();i++) {
var navTerm = navTerms.getItemAtIndex(i);
console.log(navTerm.get_id().toString());
console.log(navTerm.get_title().get_value());
console.log(navTerm.get_categoryImageUrl());
}
},
function(sender, args)
{
console.log('Request failed ' + args.get_message() + ':'+ args.get_stackTrace());
}
);
});
});
});
where
function loadNavigationTerms(navTermSetId,success,error)
{
var ctx = SP.ClientContext.get_current();
var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);
var termStore = taxonomySession.getDefaultSiteCollectionTermStore(); //retrieve default Term Store
var termSet = termStore.getTermSet(navTermSetId);
var navTermSet = SP.Publishing.Navigation.NavigationTermSet.getAsResolvedByWeb(ctx,termSet, ctx.get_web(), "GlobalNavigationTaxonomyProvider");
var navTerms = navTermSet.get_terms();
ctx.load(navTerms,'Include(Id,Title,CategoryImageUrl)');
ctx.executeQueryAsync(function(){
success(navTerms);
},
error);
}

omit certain pages from history cookie

I am using this script to store the user's history to a cookie for the last 10 pages accessed. So far I've got the script displaying the cookie data using the document.title, and url in a list.
My question is what would be the simplest way to add a page skip feature, that would let me omit certain pages from being added to the history cookie? Everything I've tried hasn't worked, as it's a little bit outside of my knowledge.
Thanks for your time and help.
JS:
(function($){
var history;
function getHistory() {
var tmp = $.cookie("history");
if (tmp===undefined || tmp===null) tmp = "";
if ($.trim(tmp)=="") tmp = [];
else tmp = tmp.split("||");
history = [];
$.each(tmp, function(){
var split = this.split("|");
history.push({
title: split[0],
url: split[1]
});
});
}
function saveHistory() {
var tmp = [];
$.each(history, function(){
tmp.push(this.title+"|"+this.url);
});
$.cookie("history",tmp.join("||"),{ expires: 60, path: "/" });
}
function addToHistory(title,url) {
var newHistory = []
$.each(history, function(){
if (this.url!=url) newHistory.push(this);
});
history = newHistory;
if (history.length>=10) {
history.shift();
}
history.push({
title: title,
url: url
});
saveHistory();
writeHistory();
}
function writeHistory() {
var list = $("<ul />");
$.each(history, function() {
var element = $("<li />");
var link = $("<a />");
link.attr("href",this.url);
link.text(this.title);
element.append(link);
list.append(element);
});
$("#history").empty().append(list);
}
$(document).ready(function(){
getHistory();
var url = document.location.href;
var split = url.split("#");
var title;
if (split.length > 1) {
title = $("#"+split[1]).text();
} else {
title = document.title;
}
if (title===undefined || title===null || $.trim(title)=="") title = url;
addToHistory(title,url);
url = split[0];
$("a[href^='#']").click(function(){
var link = $(this);
var href = link.attr("href");
var linkUrl = url+href;
var title = $(href).text();
if (title===undefined || title===null || $.trim(title)==="") title = linkUrl;
addToHistory(title,linkUrl);
});
});
})(jQuery);
HTML:
<div id="history"></div>
several ways you could approach this... You could keep an Array of urls not to save, or you could put something in the page that would let the script know not to save that page?...
function saveHistory(){
if ($('.no-save-history')) return false;
/*...*/
}
HTML:
< div id="history" class="no-save-history">

How do get param from a url

As seen below I'm trying to get #currentpage to pass client params
Can someone help out thanks.
$(document).ready(function() {
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
}
var url = $("currentpage");
// yes I relize this is the part not working.
var client = jQuery.param("currentpage");
var page = jQuery.param("currentpage");
var devurl = "http://#/?clientsNumber=" + client + "&pageName=" + page ;
});
This is a method to extract the params from a url
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Here's how to use it in your code
var url = "?c=231171&p=home";
var params = getUrlParams(url);
var devurl = "http://site.com/?c=" + encodeURIComponent(params.c) + "&p=" + encodeURIComponent(params.p) + "&genphase2=true";
// devurl == "http://site.com/?c=231171&p=home&genphase2=true"
See it in action http://jsfiddle.net/mendesjuan/TCpsD/
Here's the code you posted with minimal changes to get it working, it also uses $.param as it's intended, that is to create a query string from a JS object, this works well since my suggested function returns an object from the url
$(document).ready(function() {
// This does not handle arrays because it's not part of the official specs
// PHP and some other server side languages support it but there's no official
// consensus
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
// no need for the extra load listener here, jquery.ready already puts
// your code in the onload
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
var url = $("currentpage");
var paramMap = getUrlParams(url);
// Add the genphase parameter to the param map
paramMap.genphase2 = true;
// Use jQuery.param to create the url to click on
var devurl = "http://site.com/?"+ jQuery.param(paramMap);
$('#mydev').click( function(){
window.open(devurl);
});
});

Categories

Resources