"Page Unresponsive" Error in Chrome when trying to GET files > 500kb - javascript

I am trying to get Log files in my application, and am using Ajax to do so.
The problem is that while using Chrome I constantly get 'Page Unresponsive' Errors when I try to load the files.
My application is working fine in Firefox, so I'm guessing this is a webkit issue.
I removed xhr because I heard chrome has a problem with it.
This is my code -
$.ajax(
{
type: 'GET',
url: "Logs/GetLogFile?option=" + logFile,
data: {},
success: function (data) {
var fileData = data;
cleanUp();
currentlyViewedFile = logFile;
var fileLines = fileData.split('\n');
var htmlString = '';
var lineCount = 0;
for (var i = 0; i < fileLines.length; i++) {
lineCount = lineCount + 1;
if (i == (highlightLine - 1)) {
htmlString += '<span id="highLoc" style="display:block"><font size="4" color="red">' + lineCount + '. ' + fileLines[i] + '</font></span>';
}
else {
htmlString += '<span class="spanClass">' + lineCount + '. ' + fileLines[i];
}
var combinedLine = fileLines[i];
var isNewLogLine = false;
var newLogLineCount = 0;
while (((i + newLogLineCount + 1) < fileLines.length) && (isNewLogLine == false)) {
var NextlogLine = fileLines[i + newLogLineCount + 1].split(' ');
isNewLogLine = isLogLine(NextlogLine[0]);
if (isNewLogLine == true) {
break;
}
htmlString += fileLines[i + newLogLineCount + 1];
combinedLine += fileLines[i + newLogLineCount + 1];
newLogLineCount = newLogLineCount + 1
}
i = i + newLogLineCount;
var logLine = combinedLine.split(' ');
var logMsgStartIndex = combinedLine.indexOf(logLine[5]);
var logMsg = combinedLine.substring(logMsgStartIndex);
var obj = {
lineNos: lineCount,
date: logLine[0],
time: logLine[1],
severity: logLine[2],
logClassName: logLine[4],
logMessage: logMsg
};
fileArray.push(obj);
if ((i % 1000) == 0) {
$("#textPlace").append(htmlString);
htmlString = '';
window.scrollTo(0, 2);
}
}
fileLines = null;
$("#fetchProgress").hide();
$("#textPlace").append(htmlString);
//highlight error location
var scrollX = $("#highLoc");
if (scrollX) {
if (!scrollX[0]) return;
var scrollDistance = '{ scrollTop: ' + scrollX[0].offsetTop + '}';
var distanceInJson = eval("(" + scrollDistance + ")");
$("#mainContentBox").animate(distanceInJson, 1);
}
},
///success function end
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
});
If anyone has any ideas on how to deal with this issue, please let me know.

Related

Razor Pages Javascript Ajax not passing parameters to c#

I have a Javascript function that is meant to end with passing an array back into my c# code
I have got it to reach the c# code, but it never passes a parameter
My Javascript is as follows
var errorsubmits = [];
var filelists = [];
var nameselect = document.getElementById("username");
var nameselected = nameselect.options[nameselect.selectedIndex].text;
if (nameselected.includes("User"))
errorsubmits.push("User Name");
var prioritylevel = document.getElementById("priority");
var priorityselected = prioritylevel.options[prioritylevel.selectedIndex].text;
if (priorityselected.includes("Priority"))
errorsubmits.push("Priority");
var table = document.getElementById("FileTable");
var counter = 0;
var filename = "";
var images = "";
var envs = "";
var printmethod = "";
var encmethod = "";
var colour = "";
var commentsforprint = "";
var commentsforenclose = "";
for (var i = 1, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if (counter == 0) {
if (j == 0)
filename = table.rows[i].cells[j].children[0].value;
if (j == 1)
images = table.rows[i].cells[j].children[0].value;
if (j == 2)
envs = table.rows[i].cells[j].children[0].value;
if (j == 3)
printmethod = table.rows[i].cells[j].children[0].value;
if (j == 4)
encmethod = table.rows[i].cells[j].children[0].value;
if (j == 5)
colour = table.rows[i].cells[j].children[0].value;
}
else {
if (j == 1) {
if (table.rows[i].cells[j - 1].innerHTML.includes("Print"))
commentsforprint = table.rows[i].cells[j].children[0].value;
else
commentsforenclose = table.rows[i].cells[j].children[0].value;
}
}
}
if (i % 3 == 0) {
if (filename == "")
errorsubmits.push("Filename (row:" + i + ")");
if (images == "")
errorsubmits.push("Images (row:" + i + ")");
if (envs == "")
errorsubmits.push("Envs (row:" + i + ")");
if (printmethod.includes("Method"))
errorsubmits.push("Print Method (row:" + i + ")");
if (encmethod.includes("Method"))
errorsubmits.push("Enc Method (row:" + i + ")");
if (colour.includes("?"))
errorsubmits.push("Colour (row:" + i + ")");
// alert(filename + "\n" + images + "\n" + envs + "\n" + printmethod + "\n" + encmethod + "\n" + colour + "\n" + commentsforprint + "\n" + commentsforenclose);
filelists.push(nameselected + "\t" + priorityselected + "\t" + document.getElementById('Email').textContent + "\t" + filename + "\t" + images + "\t" + envs + "\t" + printmethod + "\t" + encmethod + "\t" + colour + "\t" + commentsforprint + "\t" + commentsforenclose)
filename = "";
images = "";
envs = "";
printmethod = "";
encmethod = "";
colour = "";
commentsforprint = "";
commentsforenclose = "";
counter = 0;
}
else {
counter++;
}
}
if (errorsubmits.length != 0) {
alert("Cannot submit!\nThe following lines need filling:\n" + errorsubmits.join("\n"));
}
else {
$.ajax({
url: '?handler=Test',
contentType: 'application/json',
data: JSON.stringify(filelists)
});
}
My C# code which is currently functionless as i cant get the data is this
public JsonResult OnGetTest(IEnumerable<object>x)
{
return new JsonResult("TEST");
}
I have done an alert(JSON.stringify(filelists)) so i know that this works
(If possible i'd like to pass the raw array rather than stringifying it but i was following another SO suggestion)
The url '?handler=Test' send request like https://localhost:44389/?handler=Test&filelists=%5B%22nameselected%22%2C%22nameselected1%22%5D, because it's a HttpGet request not a POST.
Edit as per comment
1 - Function JS :
Push any string in the array filelists, and change your data to { "filelists": JSON.stringify(filelists) }
var filelists = [];
// push strings here
$.ajax({
url: '?handler=Test',
contentType: 'application/json',
data: { "filelists": JSON.stringify(filelists) }
});
2 - In the server side
public JsonResult OnGetTest(string filelists)
{
IEnumerable<string> files = JsonConvert.DeserializeObject<IEnumerable<string>>(filelists);
return new JsonResult("TEST");
}
Note that, if you need to send javascript objects in the array, you should create classes for deserializing data.

How to process large jquery each loop without crashing browser(mainly firefox)

I made a javascript code to create some html element in parent iframe based on user selection from an iframe in a popup.
My code is given below.
The each loop may contain 50 to 150 iteration. Sometimes when I call function AddProcedures the Mozilla crashes during iteration, Is there any way to fix this issue or to reduce the browser load. I tried to put setTimeout after some code blocks but it didn't help.
I have also changed the for loop to jquery each, just to try if that helps.
var tot_codes = 0;
function doAddProcedure(thisVal,resolve){
var enc_id = $("#cpt_encounter").val();
var rowId = window.parent.$("[data-encounterBilled='"+ enc_id +"']").closest('tr').attr('id'); // table row ID
var recalc = parseInt(rowId.substring(rowId.indexOf('id-')+3));
var countval = $("#last_id").val();
//Load issue Fix
//Old code
//for (i = 0; i < document.cpt.elements.length; i++) {
//if (document.cpt.elements[i].type == "checkbox") {
//if (document.cpt.elements[i].checked == true) {
$('#cpt input:checkbox:checked').each(function(){
setTimeout(function() { }, 100);
var currentCodeMod = $(this).attr("data-codemod");
var currentCodeTypid = $(this).attr("data-codeTypeid");
if (currentCodeMod == null)
return;
tot_codes++;
var nextcntval = parseInt(countval) + 1;
var code_no = $(this).attr("id").replace("cpt_chkbx", "");
var Code = $("#codeVal" + code_no).val();
var just = $("#codeType" + code_no).val();
var categoryId = $("#codeType" + code_no).data("categoryid"); //Added to get category //Bug Fix
var Name = $("#cpttext" + code_no).val();
var codedisp = Code + ':' + Name;
var Modifier = '';
//if($("#modifier_setngs").val() == 1){
var Modifier1 = $("#modcpt1"+code_no).val() != '' ? $("#modcpt1"+code_no).val() + ":" : '';
var Modifier2 = $("#modcpt2"+code_no).val() != '' ? $("#modcpt2"+code_no).val() + ":" : '';
var Modifier3 = $("#modcpt3"+code_no).val() != '' ? $("#modcpt3"+code_no).val() + ":" : '';
var Modifier4 = $("#modcpt4"+code_no).val() != '' ? $("#modcpt4"+code_no).val() + ":" : '';
Modifier = Modifier1 + Modifier2 + Modifier3 + Modifier4;
//}
var codetableid = $("#code_tab_id" + code_no).val();
var j = countval; /* lineitem wise uniqid */
//var encounter = window.parent.$('#codetype-' + j).closest('tr.charge-entry-row').find('.expand-actions').attr('data-encounterid');
var encounter = enc_id;
var codeforarr = encounter + ':' + just + ':' + Code + '::' + Modifier;
window.parent.pushToArray(codeforarr);
var f = 0;
$(window.parent.$("#codetype-" + countval).parents().find('.inner-table .charge-entry-row')).each(function() {
//console.log($(this).find('.inputStringHidden').val() + '/' + codeforarr);
if ($(this).find('.inputStringHidden').val() == codeforarr) {
var exis_row_id = $(this).find('.inputStringHidden').attr('id').split('inputStringHidden-');
j = exis_row_id[1].toString();
f = 1;
$(this).find('.front_pay_codes_display').trigger('click');
}
});
if (f == 0) {
if (window.parent.document.getElementById('inputStringHidden-' + countval).value != '') {
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = parseInt(countval) + 1;
j = countval.toString();
}
window.parent.$("#add-" + countval).trigger("click");
window.parent.$("#codetype-" + (countval)).val(currentCodeTypid);
window.parent.$("#codetype-" + countval).trigger("change");
}
window.parent.document.getElementById('inputString' + j).value = codedisp;
window.parent.document.getElementById('category-' + j).value = categoryId; //Added to set category //Bug Fix
window.parent.document.getElementById('string_id' + j).value = Code;
window.parent.document.getElementById('string_value' + j).value = Name;
window.parent.document.getElementById('inputStringHidden-' + j).value = codeforarr;
window.parent.document.getElementById('codetableid-' + j).value = codetableid;
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.val-change-bit').val(1);
setTimeout(function() {}, 100);
window.parent.$("#suggestions" + j).hide();
window.parent.$("#inputString" + j).focus();
var uniqidHidden = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.uniqid-hidden').val();
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').text(Modifier);
//if($("#modifier_setngs").val() == 1){
if (f == 0) {
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').addClass('area-hide');
}else{
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').removeClass('area-hide');
}
window.parent.$('#modifiers' + uniqidHidden).val(Modifier);
arr = Modifier.split(':');
window.parent.$('#modifier-' + uniqidHidden + '-1').val(arr[0]);
window.parent.$('#modifier-' + uniqidHidden + '-2').val(arr[1]);
window.parent.$('#modifier-' + uniqidHidden + '-3').val(arr[2]);
window.parent.$('#modifier-' + uniqidHidden + '-4').val(arr[3]);
//}
var eclaimPlanActive = window.parent.$('#eclaimPlanActive').val();
var price = $("#cpt_price" + code_no).val();
var price_level = $("#pricelevelhidden" + code_no).val();
if (price == 0 || price == null)
price = 0;
window.parent.$('#price-' + j).val(price);
window.parent.$('#bill-pricelevel-' + j).val(price_level);
/** Charge Total **/
var chargeTotal = window.parent.$('#charge-total').text().replace(/[\s\,]/g, '').trim();
if (chargeTotal == '')
chargeTotal = parseFloat(0);
var tempChargeTotal = parseFloat(chargeTotal) + parseFloat(price);
window.parent.$('#charge-total span').html(tempChargeTotal);
/** End **/
var units = $("#cpt_units" + code_no).val(); //data[0]['units']
if (units == 0 || units == null)
units = 1;
window.parent.$('#qty-' + j).val(units);
var tax = 0;
var disc = 0;
setTimeout(function() { }, 100);
if (window.parent.$('#tax-' + j).length > 0)
tax = window.parent.$('#tax-' + j).val().replace(/[\s\,]/g, '');
if (window.parent.$('#discount-' + j).length > 0)
disc = window.parent.$('#discount-' + j).val().replace(/[\s\,]/g, '');
var amount = price * units;
amount = amount + ((amount * tax) / 100);
if (disc > 0) {
var p = price * units;
var dc = ((p * disc) / 100);
amount = amount - dc;
}
/** Discount Total **/
var disTotal = window.parent.$('#discount-total').text().replace(/[\s\,]/g, '').trim();
if (disTotal == '')
disTotal = parseFloat(0);
var tempDisTotal = parseFloat(disTotal) + parseFloat(dc);
if (isNaN(tempDisTotal) == true) {
tempDisTotal = '0.00';
}
window.parent.$('#discount-total').html(tempDisTotal);
/** End **/
if (!parseFloat(window.parent.$('#lineitempaid-' + j).val()))
window.parent.$('#lineitempaid-' + j).val('0.00');
window.parent.$('#total-' + j).val(amount);
window.parent.$('#remainder-' + j).val(amount);
window.parent.$('#hidremainder-' + j).val(amount);
//insurance and patient_share
if (eclaimPlanActive == '1') {
var codetableid = window.parent.$('#codetableid-' + j).val();
var parentRowVal = parseInt(window.parent.$('#codetableid-' + j).closest('tr').find('.row_value').attr('data-rowvalue')) - 1;
var insData1 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata1');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData1);
if (window.parent.$('#have-benefit').val() == '0') {
var insData2 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata2');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData2);
}
}
var passParams = '';
window.parent.calculate('qty-' + j, passParams);
//Updating the title
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.fi-searchitems').attr('data-original-title', codedisp);
if (f == 0) {
//Display DIv :: Relace with new values
var cloneLabel = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').clone();
//In Edit Mode
if (cloneLabel.find('.displaymode-elem').length > 0) {
var $max_length = 16;
var trucncateCode = Name;
if (trucncateCode.length > $max_length)
trucncateCode = trucncateCode.substring(0, $max_length) + '...';
cloneLabel.find('.front_pay_codetype').text(just + ":");
cloneLabel.find('.front_pay_code').text(trucncateCode);
cloneLabel.find('.displaymode-elem').removeClass('area-hide');
cloneLabel.removeClass('area-hide');
cloneLabel.find("input[name='code_type']").val(just).attr('id', 'code_type-' + j);
cloneLabel.find("input[name='string_id']").val(Code).attr('id', 'string_id-' + j);
cloneLabel.find("input[name='string_value']").val(Name);
var dataType = $("#inputString" + j).closest('tr.charge-entry-row').find('.data_type').val();
if (dataType == "lab") {
var lab = $("select[name='lab_type']").find('option:selected').val();
if (cloneLabel.find("input[name='lab_type']").length > 0) {
cloneLabel.find("input[name='lab_type']").val(lab);
} else {
cloneLabel.append('<input type="hidden" name="lab_type" class="lab_type" value="' + lab + '">');
}
} else {
cloneLabel.find("input[name='lab_type']").remove();
}
setTimeout(function() { }, 100);
//Making the view
cloneLabel.removeClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.front_pay_codes_editelem').removeClass('area-show').addClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').replaceWith(cloneLabel);
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_autosuggest').html('');
}
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = nextcntval.toString();
}
else {
window.parent.$("#suggestions" + j).hide();
countval = countval.toString();
}
setTimeout(function() { }, 150);
});
window.parent.reCalculatePlanEncounterWise(recalc);
resolve("Success!");
}
function doAddPromise(thisVal){
return new Promise(function(resolve){
doAddProcedure(thisVal,resolve);
});
}
function AddProcedures(thisval)
{
$('#procedureSaveButton').text('Processing....');
// $('.fa-spinner').removeClass('hide');
top.ShowAjaxLoader('Loading..');
setTimeout(function(){
}, 2000);
//top.ShowAjaxLoader('Loading..');
setTimeout(function(){
$.when(doAddPromise(thisval)).done(function(){
if (tot_codes > 0) {
window.parent.phFrntpayClosePopup();
top.notification('Successfully added the procedures.');
//top.HideAjaxLoader('Loading..');
top.HideAjaxLoader();
$('body').removeClass('modal-open');
} else {
top.notification('Please select atleast one procedure.');
$('#procedureSaveButton').text('Add Procedures');
//$('.fa-spinner').addClass('hide');
top.HideAjaxLoader();
}
});
}, 10);
}

Highlight.js and Showdown.js not work together

I am trying to be able to use highlight.js when my preview is enabled
Unable to get the highlightjs to work with my preview using showdown.js
Question: How to get the highlight.js to work with showdown.js
Codepen Demo Note all the .js files and css files are loaded in the codepen settings
I have tried using
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
Full Script
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
})
$('#button-link').on('click', function() {
$('#myLink').modal('show');
});
$('#button-image').on('click', function() {
$('#myImage').modal('show');
});
$('#button-smile').on('click', function() {
$('#mySmile').modal('show');
});
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#link_title').val(selectedText);
$('#link_url').val('http://');
});
$('#myImage').on('shown.bs.modal', function() {
$("#image_url").attr("placeholder", "http://www.example.com/image.png");
});
$("#save-image").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
var replace_word = '![enter image description here]' + '[' + counter + ']';
if (counter == 1) {
if ($('input#image_width').val().length > 0) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val() + ' =' + $('input#image_width').val() + 'x' + $('input#image_height').val();
} else {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
$("#save-link").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($('#link_title').val().length > 0) {
var replace_word = '[' + $('#link_title').val() + ']' + '[' + counter + ']';
} else {
var replace_word = '[enter link description here]' + '[' + counter + ']';
}
if (counter == 1) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#link_url').val();
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#link_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
// Editor Buttons
$('#bold').on('click', function(e) {
text_wrap("message", "**", "**", 'strong text');
});
$('#italic').on('click', function(e) {
text_wrap("message", "*", "*", 'emphasized text');
});
$('#quote').on('click', function(e) {
text_wrap("message", "> ", "", 'Blockquote');
});
$('#code').on('click', function(e) {
code_wrap("message", "", "", 'enter code here');
});
function text_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
if (selectedText.length > 0) {
replacement = openTag + selectedText + closeTag;
} else {
replacement = openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function code_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var multiLineReplace = '\n' + openTag;
if (selectedText.length > 0) {
//using regex to replace all instances of `\n` with `\n` + your indent spaces.
replacement = ' ' + openTag + selectedText.replace(/\n/g, multiLineReplace) + closeTag;
} else {
replacement = ' ' + openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function findAvailableNumber(textarea) {
var number = 1;
var a = textarea.value;
if (a.indexOf('[1]') > -1) {
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match) {
return parseInt(match.match(/\d+/)[0]);
});
//Find first unused number
var number = 1;
while (true) {
if (usedNumbers.indexOf(number) === -1) {
//Found unused number
return number;
}
number++;
}
}
return number;
}
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
$(function() {
$('[data-toggle="tooltip"]').tooltip()
});

Multiple Group By using two look-up columns which have multi valued selection enabled on an SP 2013 list using JavaScript

So I'm working on SP 2013 and have a document library which has three Lookup columns viz : Business Unit, Axis Product and Policy form. What I'm trying to do is I have managed to group by the List items first by Business Unit column and then by the Axis Product Column. This works fine but recently I'm trying to show the count of the number of items inside a particular Axis Product. Which would be like - Axis Product : "Some Value" (Count).
I'm able to show this count with Business Unit, but not able to do this with Axis Product. So I tried querying the library with both Business Unit and Axis Product to get the count for Axis Product, I'm not sure about this approach and currently I'm getting an error message:
'collListItemAxisProduct' is undefined.
Any help would be appreciated as I've been stuck on this for a long time now. Here is my code below :
// JavaScript source code
$(function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', oGroupBy.GetDataFromList);
});
function GroupBy()
{
this.clientContext = "";
this.SiteUrl = "/sites/insurance/products";
this.lookUpLIst = "AxisBusinessUnit";
this.AxisProductlookUpList = "AXIS Product";
this.lookUpItems = [];
this.lookUpColumnName = "Title";
this.AxisProductlookupItems = [];
this.AProducts = [];
this.index = 0;
this.secondindex = 0;
this.parentList = "AXIS Rules Library";
this.html = "<div id='accordion'><table cellspacing='35' width='100%'><tr><td width='8%'>Edit</td><td width='13%'>Name</td><td width='13%'>Modified</td><td width='13%'>Underwriting Comments</td><td width='13%'>Policy Form Applicability</td><td width='13%'>AXIS Product</td><td width='13%'>Business Unit</td></tr>";
}
function MultipleGroupBy()
{
this.AxProducts = [];
this.SecondaryGroupBy = [];
this.count = "";
this.BusinessUnit = "";
this.html = "";
}
function UI()
{
this.id = "";
this.name = "";
this.modified = "";
this.acturialComments = "";
this.underWritingComments = "";
this.policyFormApplicability = [];
this.axisProduct = [];
this.businessUnit = [];
this.itemcheck = "";
this.Count = 0;
this.header = "";
this.AxisProductCount = 0;
this.trID = "";
this.SecondaryID = "";
this.LandingUrl = "&Source=http%3A%2F%2Fecm%2Ddev%2Fsites%2FInsurance%2FProducts%2FAXIS%2520Rules%2520Library%2FForms%2FGroupBy%2Easpx";
}
var oUI = new UI();
var oGroupBy = new GroupBy();
var oMultipleGroupBy = new MultipleGroupBy();
GroupBy.prototype.GetDataFromList = function () {
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.lookUpLIst);
var APList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.AxisProductlookUpList);
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
var secondcamlQuery = new SP.CamlQuery();
this.secondListItem = APList.getItems(secondcamlQuery);
oGroupBy.clientContext.load(collListItem);
oGroupBy.clientContext.load(secondListItem);
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.BindDataFromlookUpList), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.BindDataFromlookUpList = function (seneder,args) {
var listenumerator = collListItem.getEnumerator();
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
oGroupBy.lookUpItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
GroupBy.prototype.GetDataFromParent = function(lookUpItems)
{
var oList1 = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Business_x0020_Unit\'/>' +
'<Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq></Where></Query></View>');
this.collListItem1 = oList1.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItem1, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.CreateHTMLGroupBy), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.CreateHTMLGroupBy = function (sender,args)
{
var listenumerator = this.collListItem1.getEnumerator();
var axisproductlistenumarator = secondListItem.getEnumerator();
while (axisproductlistenumarator.moveNext()) {
var currentitem = axisproductlistenumarator.get_current(); oGroupBy.AxisProductlookupItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oUI.Count = this.collListItem1.get_count();
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oUI.trID = oGroupBy.lookUpItems[oGroupBy.index];
oMultipleGroupBy.BusinessUnit = oGroupBy.lookUpItems[oGroupBy.index];
oGroupBy.html = oGroupBy.html + "<table style='cursor:pointer' id='" + oUI.trID.replace(" ", "") + "' onclick='javascript:oUI.Slider(this.id)'><tr><td colspan='7'><h2 style='width:1100px;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>Business Unit : " + oGroupBy.lookUpItems[oGroupBy.index] + " " + "<span> (" + oUI.Count + ")</span></h2></td></tr></table>";
}
oUI.businessUnit.length = 0;
oMultipleGroupBy.SecondaryGroupBy.length = 0;
oMultipleGroupBy.SecondaryGroupBy.push(oUI.trID);
oMultipleGroupBy.html = "";
if (oUI.Count > 0) {
if (listenumerator != undefined) {
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
if (currentitem != undefined) {
oUI.id = currentitem.get_item("ID");
oUI.name = currentitem.get_item("FileLeafRef");
oUI.modified = currentitem.get_item("ModifiedDate");
//oUI.policyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
oUI.underWritingComments = currentitem.get_item("Underwriting_x0020_Comments");
//oUI.axisProduct = currentitem.get_item("AXIS_x0020_Product");
var lookupPolicyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
var lookupField = currentitem.get_item("Business_x0020_Unit");
var lookupAxisProduct = currentitem.get_item("AXIS_x0020_Product");
oUI.businessUnit.length = 0;
for (var i = 0; i < lookupField.length; i++) { oUI.businessUnit.push(lookupField[i].get_lookupValue());
}
oUI.axisProduct.length = 0;
for (var m = 0; m < lookupAxisProduct.length; m++) { oUI.axisProduct.push(lookupAxisProduct[m].get_lookupValue());
}
oUI.policyFormApplicability.length = 0;
for (var a = 0; a < lookupPolicyFormApplicability.length; a++)
{
oUI.policyFormApplicability.push(lookupPolicyFormApplicability[a].get_lookupValue());
}
oGroupBy.CreateUI(oUI);
}
}
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oGroupBy.html = oGroupBy.html + oMultipleGroupBy.html;
}
}
}
oGroupBy.index = oGroupBy.index + 1;
if (oGroupBy.index <= oGroupBy.lookUpItems.length) {
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
if(oGroupBy.index == oGroupBy.lookUpItems.length + 1)
{
oGroupBy.html = oGroupBy.html + "</table></div>";
$("#contentBox").append(oGroupBy.html);
$(".hide,.sd-hide").hide();
}
}
UI.prototype.Slider = function (id) {
$("#MSOZoneCell_WebPartWPQ3").click();
//$(".hide").hide();
var elements = document.querySelectorAll('[data-show="' + id + '"]');
$(elements).slideToggle();
}
UI.prototype.SecondarySlider = function (id) {
var elements = document.querySelectorAll('[data-secondary="' + id + '"]');
$(elements).slideToggle();
}
GroupBy.prototype.CreateUI = function (oUI) {
var BusinessUnit = "";
var AxisProduct = "";
var Policyformapplicability = "";
var tempBUnit = "";
for (var i = 0; i < oUI.businessUnit.length; i++) {
BusinessUnit = BusinessUnit + oUI.businessUnit[i] + ",";
}
for (var m = 0; m < oUI.axisProduct.length; m++) {
AxisProduct = AxisProduct + oUI.axisProduct[m] + ",";
}
for (var a = 0; a < oUI.policyFormApplicability.length; a++) {
Policyformapplicability = Policyformapplicability + oUI.policyFormApplicability[a] + ",";
}
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList1SecondGroupBy = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Business_x0020_Unit\' /><Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq>' +
'<Eq><FieldRef Name=\'AXIS_x0020_Product\' /><Value Type=\'LookupMulti\'>' + oGroupBy.AxisProductlookupItems[oGroupBy.secondindex] + '</Value></Eq></And></Where><OrderBy><FieldRef Name=\'Title\' Ascending=\'True\' /></OrderBy></Query><View>');
this.collListItemAxisProduct = oList1SecondGroupBy.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItemAxisProduct, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
if (collListItemAxisProduct != undefined) {
//oGroupBy.clientContext.load(collListItemAxisProduct);
var AxisProductlistenumerator = this.collListItemAxisProduct.getEnumerator();
if (AxisProductlistenumerator != undefined) {
oUI.AxisProductCount = this.collListItemAxisProduct.get_count();
oGroupBy.AProducts.length = 0;
if (AxisProduct != "") {
oGroupBy.AProducts = AxisProduct.split(',');
}
oGroupBy.AProducts.splice(oGroupBy.AProducts.length - 1, 1);
//alert(oGroupBy.AProducts.length);
var link = "/sites/Insurance/Products/AXIS%20Rules%20Library/Forms/EditForm.aspx?ID=" + oUI.id + oUI.LandingUrl;
var editicon = "/sites/insurance/products/_layouts/15/images/edititem.gif?rev=23";
for (var i = 0; i < oGroupBy.AProducts.length; i++) {
var SecondaryGBTableID = "";
if (oGroupBy.AProducts[i].replace(" ", "") != "") {
SecondaryGBTableID = oGroupBy.AProducts[i].replace(/\s/g, "") + oMultipleGroupBy.BusinessUnit.replace(/\s/g, "");
SecondaryGBTableID = SecondaryGBTableID.replace("&", "");
var isPresent = $.inArray(oGroupBy.AProducts[i].replace(/\s/g, ""), oMultipleGroupBy.SecondaryGroupBy);
}
oUI.SecondaryID = oUI.trID.replace("/\s/g", "") + oGroupBy.AProducts[i].replace("/\s/g", "");
if ((isPresent <= -1)) {
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr style='margin-left:10px;margin-bottom:1px solid grey;' cellspacing='36'><td ><h3 class='hide' onclick='javascript:oUI.SecondarySlider(this.id);' id='" + oUI.SecondaryID + "' data-show='" + oUI.trID.replace(" ", "") + "' style='cursor:pointer;width:100%;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>    -    AXIS Product : " + oGroupBy.AProducts[i] + " " + "<span> (" + oUI.AxisProductCount + ")</span></h3></td></tr>";
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr><td><table class='hide' data-show='" + oUI.trID.replace(" ", "") + "' width='100%' cellspacing='36' id='" + SecondaryGBTableID + "'><tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr></table></td></tr>";
}
else {
if ($("#" + SecondaryGBTableID).html() != undefined) {
$("#" + SecondaryGBTableID).append("<tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr>");
oMultipleGroupBy.html = $("#divMultiplegroupBy").html();
}
}
document.getElementById("divMultiplegroupBy").innerHTML = oMultipleGroupBy.html;
if ((isPresent <= -1) && (oGroupBy.AProducts[i] != "")) {
oMultipleGroupBy.SecondaryGroupBy.push(oGroupBy.AProducts[i].replace(/\s/g, ""));
}
}
}
}
else {
oGroupBy.secondindex = oGroupBy.secondindex + 1;
oGroupBy.CreateUI(oUI);
}
}
GroupBy.prototype.onError = function (sender, args) {
alert('Error: ' + args.get_message() + '\n');
}
// JavaScript source code
You have to call clientContext.executeQueryAsync after calling clientContext.load in order to populate any results from the SharePoint object model.
executeQueryAsync takes two parameters: first the function to execute on success, and second the function to execute if an error is encountered. Any code that depends on successfully loading values from the query should be placed in the on success function.

Javascript Hanging UI on IE6/7

Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?

Categories

Resources