Trying to change parameters in JQuery plugin file - javascript

I have a JQuery plugin i am using as part of my project. The file is located in the root of my solution folder under a file called "jquery.tablePagination.js" I want to alter some of the parameters inside of the file without hard coding the data.
The script is as follows..
(function ($) {
$.fn.tablePagination = function (settings) {
var defaults = {
firstArrow: (new Image()).src = "./images/first.gif",
prevArrow: (new Image()).src = "./images/prev.gif",
lastArrow: (new Image()).src = "./images/last.gif",
nextArrow: (new Image()).src = "./images/next.gif",
rowsPerPage: 5,
currPage: 1,
optionsForRows: [5, 10],
ignoreRows: []
};
settings = $.extend(defaults, settings);
return this.each(function () {
var table = $(this)[0];
var totalPagesId = '#' + table.id + '+#tablePagination #tablePagination_totalPages';
var currPageId = '#' + table.id + '+#tablePagination #tablePagination_currPage';
var rowsPerPageId = '#' + table.id + '+#tablePagination #tablePagination_rowsPerPage';
var firstPageId = '#' + table.id + '+#tablePagination #tablePagination_firstPage';
var prevPageId = '#' + table.id + '+#tablePagination #tablePagination_prevPage';
var nextPageId = '#' + table.id + '+#tablePagination #tablePagination_nextPage';
var lastPageId = '#' + table.id + '+#tablePagination #tablePagination_lastPage';
var possibleTableRows = $.makeArray($('tbody tr', table));
var tableRows = $.grep(possibleTableRows, function (value, index) {
return ($.inArray(value, defaults.ignoreRows) == -1);
}, false)
var numRows = tableRows.length
var totalPages = resetTotalPages();
var currPageNumber = (defaults.currPage > totalPages) ? 1 : defaults.currPage;
if ($.inArray(defaults.rowsPerPage, defaults.optionsForRows) == -1)
defaults.optionsForRows.push(defaults.rowsPerPage);
function hideOtherPages(pageNum) {
if (pageNum == 0 || pageNum > totalPages)
return;
var startIndex = (pageNum - 1) * defaults.rowsPerPage;
var endIndex = (startIndex + defaults.rowsPerPage - 1);
$(tableRows).show();
for (var i = 0; i < tableRows.length; i++) {
if (i < startIndex || i > endIndex) {
$(tableRows[i]).hide()
}
}
}
function resetTotalPages() {
var preTotalPages = Math.round(numRows / defaults.rowsPerPage);
var totalPages = (preTotalPages * defaults.rowsPerPage < numRows) ? preTotalPages + 1 : preTotalPages;
if ($(totalPagesId).length > 0)
$(totalPagesId).html(totalPages);
return totalPages;
}
function resetCurrentPage(currPageNum) {
if (currPageNum < 1 || currPageNum > totalPages)
return;
currPageNumber = currPageNum;
hideOtherPages(currPageNumber);
$(currPageId).val(currPageNumber)
}
function resetPerPageValues() {
var isRowsPerPageMatched = false;
var optsPerPage = defaults.optionsForRows;
optsPerPage.sort();
var perPageDropdown = $(rowsPerPageId)[0];
perPageDropdown.length = 0;
for (var i = 0; i < optsPerPage.length; i++) {
if (optsPerPage[i] == defaults.rowsPerPage) {
perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i], true, true);
isRowsPerPageMatched = true;
}
else {
perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i]);
}
}
if (!isRowsPerPageMatched) {
defaults.optionsForRows == optsPerPage[0];
}
}
function createPaginationElements() {
var htmlBuffer = [];
htmlBuffer.push("<div id='tablePagination'>");
htmlBuffer.push("<span id='tablePagination_perPage'>");
htmlBuffer.push("<select id='tablePagination_rowsPerPage'><option value='5'>5</option></select>");
htmlBuffer.push("per page");
htmlBuffer.push("</span>");
htmlBuffer.push("<span id='tablePagination_paginater'>");
htmlBuffer.push("<img id='tablePagination_firstPage' src='" + defaults.firstArrow + "'>");
htmlBuffer.push("<img id='tablePagination_prevPage' src='" + defaults.prevArrow + "'>");
htmlBuffer.push("Page");
htmlBuffer.push("<input id='tablePagination_currPage' type='input' value='" + currPageNumber + "' size='1'>");
htmlBuffer.push("of <span id='tablePagination_totalPages'>" + totalPages + "</span>");
htmlBuffer.push("<img id='tablePagination_nextPage' src='" + defaults.nextArrow + "'>");
htmlBuffer.push("<img id='tablePagination_lastPage' src='" + defaults.lastArrow + "'>");
htmlBuffer.push("</span>");
htmlBuffer.push("</div>");
return htmlBuffer.join("").toString();
}
if ($(totalPagesId).length == 0) {
$(this).after(createPaginationElements());
}
else {
$('#tablePagination_currPage').val(currPageNumber);
}
resetPerPageValues();
hideOtherPages(currPageNumber);
$(firstPageId).bind('click', function (e) {
resetCurrentPage(1)
});
$(prevPageId).bind('click', function (e) {
resetCurrentPage(currPageNumber - 1)
});
$(nextPageId).bind('click', function (e) {
resetCurrentPage(currPageNumber + 1)
});
$(lastPageId).bind('click', function (e) {
resetCurrentPage(totalPages)
});
$(currPageId).bind('change', function (e) {
resetCurrentPage(this.value)
});
$(rowsPerPageId).bind('change', function (e) {
defaults.rowsPerPage = parseInt(this.value, 10);
totalPages = resetTotalPages();
resetCurrentPage(1)
});
})
};
})(jQuery);
I want to be able to alter the following settings: RowsPerPage and OptionforRows.
I have tried to copy and paste the code from the script directly into my .aspx file next to some other Jquery/JavaScript I already have however the plugin doesn't run when I do this.
Could it be possible to write to the settings part of the file from the code behind? It would also work if the file could read the settings from a certain hidden field but I can't get it to run on my .aspx to do this. I'm not sure how to go about solving this issue.

I have ended up solving this issue by first copying the script and pasting in my .aspx file. I was originally copying the code inside of the document ready function:
$(document).ready(function)
Once I have had this done It was quite easy to pass through a variable from the code behind to be used as the required setting.
rowsPerPage: <%=PageRowAmount%>,
For the code behind I have added the following:
Public PageRowAmount As Integer = 10
and in the page_load I have added
Page.DataBind()
Solved!

Related

Pass value from .gs to htmlService

I'm quite new to GAS & JS so please bear with me.
Problem 1 solved by #Cooper
I'm trying to pass the pdf link that gets generated by pdf.gs to an href in PDFlinkHTML.html.
I initially just had a Html output in the generatePDF() function and used href:"${pdf.getURl()}" but this is not viable anymore since the htmlService uses a lot of CSS, jQuery and needs a separate File.
Problem 2
I also have a loading spinner (essentially just a fixed div) in my htmlService which i want to hide (with either pure JS or jQuery) as soon as the PDF is generated and the link has been passed on to the href.
(My current "workaround" is just displaying the loading spinner in a separate ModalDialog at the start of the function & the PDFlinkHTML.html the at the end. Looks fine but feels cheap.)
I'd really appreciate some help & input.
Regards
pdf.gs
function createPDF(ssId, sheet, pdfName, lr) {
const fr = 0, fc = 0, lc = 9;
const url = "https://docs.google.com/spreadsheets/d/" + ssId + "/export" +
"?format=pdf&" +
"size=7&" +
"fzr=true&" +
"portrait=true&" +
"fitw=true&" +
"gridlines=false&" +
"printtitle=false&" +
"top_margin=0.5&" +
"bottom_margin=0.25&" +
"left_margin=0.5&" +
"right_margin=0.5&" +
"sheetnames=false&" +
"pagenum=UNDEFINED&" +
"attachment=true&" +
"gid=" + sheet.getSheetId() + '&' +
"r1=" + fr + "&c1=" + fc + "&r2=" + lr + "&c2=" + lc;
const params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
const blob = UrlFetchApp.fetch(url, params).getBlob().setName(pdfName + '.pdf');
const destinationFolder = DriveApp.getFolderById('1BI_cD628wyqHWgagwmkxYBhvHo1irrQY'); // PDF destination folder
const pdfFile = destinationFolder.createFile(blob);
return pdfFile;
}
function generatePDF() {
var lock = LockService.getScriptLock();
try {
lock.waitLock(20000); // Attempts to acquire the lock, timing out with an exception after 20 seconds
} catch (e) {
Logger.log('Could not obtain lock after 20 seconds.');
return Browser.msgBox("Server beschäftigt bitte versuche es in einem Moment erneut.");
};
var html = HtmlService.createTemplateFromFile('PDFloadingHTML')
.evaluate()
.setWidth(400)
.setHeight(250);
ui.showModalDialog(html, "‎");
const templateSheet = SpreadsheetApp.openById('1entOMh9MqliPJjQm7W9loDYeghJEnqTCqcaXDoU1FCc');
const destinationSS = templateSheet.copy('Inventory');
const destinationSheet = destinationSS.getSheets()[0];
const destinationID = destinationSS.getId();
const f2 = iSheet.getRange(2, 6).getValue();
const timestamp = Utilities.formatDate(new Date(), "GMT+2", "yyyy/MM/dd HH:mm");
const pdfname = "" + f2 + " " + timestamp + ""; // PDF output name
// PDF generation & cleanup.
sortedArr = sortRange();
var letter = "";
var counter = 0;
var i = 5;
while (!destinationSheet.getRange(i, 1).isBlank()) {
if (destinationSheet.getRange(i, 1).getValue().toString().trim().length == 1) {
letter = destinationSheet.getRange(i, 1).getValue().toString().trim().toLowerCase();
} else if (String(sortedArr[counter]).trim().toLowerCase().startsWith(letter) && String(sortedArr[counter]).trim().toLowerCase() != "undefined") {
destinationSheet.getRange(i, 1).setValue(sortedArr[counter][0]);
destinationSheet.getRange(i, 2).setValue(sortedArr[counter][1]);
counter += 1;
for (var j = counter; j < sortedArr.length; j++) {
if (String(sortedArr[counter]).trim().toLowerCase().startsWith(letter)) {
destinationSheet.insertRowAfter(i);
if (letter == "z") {
destinationSheet.getRange(i, 1, 1, 9).copyTo(destinationSheet.getRange(i + 1, 1, 1, 2), { formatOnly: true });
} else {
destinationSheet.getRange(i, 1, 1, 2).copyTo(destinationSheet.getRange(i + 1, 1, 1, 2), { formatOnly: true });
};
i += 1;
destinationSheet.getRange(i, 1).setValue(sortedArr[counter][0]);
destinationSheet.getRange(i, 2).setValue(sortedArr[counter][1])
counter += 1;
};
};
} else {
destinationSheet.getRange(i, 1).setValue("-");
destinationSheet.getRange(i, 2).setValue("-");
};
i += 1;
};
SpreadsheetApp.flush();
destinationSheet.autoResizeColumns(2, 1);
Utilities.sleep(500); // Using to offset any potential latency in creating .pdf
const pdf = createPDF(destinationID, destinationSheet, pdfname, destinationSheet.getLastRow());
DriveApp.getFileById(destinationID).setTrashed(true);
var html = HtmlService.createTemplateFromFile('PDFlinkHTML')
.evaluate()
.setWidth(400)
.setHeight(250);
ui.showModalDialog(html, "‎");
return;
}
function sortRange() {
arr = iSheet.getRange(`D6:E${iSheet.getLastRow()}`).getDisplayValues();
arr.sort(function (x, y) {
var xp = x[0];
var yp = y[0];
return xp == yp ? 0 : xp < yp ? -1 : 1;
});
return arr;
}
How about something like this:
var temp = HtmlService.createTemplateFromFile('PDFlinkHTML')
temp.pdflink = pdflinkData;
var html = temp.evaluate().setWidth(400).setHeight(250);
ui.showModalDialog(html, "‎");
href= <?= pdflink ?>

Column filtering and stacking on table not working on backspace in input

I have created my table with jQuery and have it using filtering on the column. However, ran into something interesting.
Below is my fiddle
https://jsfiddle.net/4sy5dweg/1/
So my issue is as follows -
Once I find what I am looking for by filtering. If I decided to start backspacing I want it to continue searching that column and obviously start going backwards on searching.
I hope that makes sense.
$.extend($.expr[":"], {
"containsIN": function (elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
$("[id*=TXTSEARCH]").keyup(function () {
tablename = $(this).closest('table').attr('id');
mytd = $(this).closest('th');
var indexColumn = mytd.index();
var data = this.value.toLowerCase().split(" ");
var jo = $("[id*=" + tablename + "]").find("tr:not(:first)");
jo.filter(function (i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":not(:containsIN('" + data[d] + "'))")) {
console.log(data[d]);
return true;
}
}
return false;
}).hide();
})
I know the issue has to do with hiding that row on initial search. However, somehow for isntance if someone has a typo and goes to backspace it wont show anything because that row is still hidden. Is there a way to keep the other filters in place and basically remove the filter from the row being corrected?
I hope I am making sense.
Update I have attempted the following -
$("[id*=TXTSEARCH]").keyup(function () {
var tablename = $(this).closest('table').attr('id');
console.log(tablename);
var FindMyRow;
$("#" + tablename).find('th:visible').find($("[id*=TXTSEARCH]")).each(function () {
FindMyRow = $(this).closest('th:visible');
var indexColumn = FindMyRow.index();
console.log($(this).attr('id') + " " + indexColumn);
var data = this.value.toLowerCase().split(" ");
var jo = $("[id*=" + tablename + "]").find("tr:not(:first)");
jo.show().filter(function (i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":not(:containsIN('" + data[d] + "'))")) {
console.log(data[d]);
return true;
}
}
return false;
}).hide();
});
to no avail.
Decided to change my way of doing it.
I added a button to each column header that the user can click on so that if they make a type they just check it before clicking it.
$("[id*=BTNSEARCH]").click(function (e) {
e.preventDefault();
var tablename = $(this).closest('table').attr('id');
mytd = $(this).closest('th');
var TextBoxToSearch = ($(this).prev('input').val());
var indexColumn = mytd.index();
FindMyRow = $(this).closest('th:visible');
var indexColumn = FindMyRow.index();
var data = TextBoxToSearch.toLowerCase().split(" ");
var jo = $("#" + tablename).find("tr:not(:first)");
jo.filter(function (i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":not(:containsIN('" + data[d] + "'))")) {
return true;
}
}
return false;
}).hide();
})

How to store drag&drop to local storage

hope you can help!
I am working on a school assignment with local storage and drag & drop, so I am very new to this. I'm making a kind of task manager, similar to Trello, with tasks, members and different lists.
The problem I am having is that the things I drag are "reset" if I refresh the page. How can I fix it so it stays where I drop it?
Here the tasks are created:
function renderTasks() {
var outputTask = JSON.parse(window.localStorage.getItem("outputTask")) || [];
var outputTaskEl = document.getElementById("outputTasks");
outputTaskEl.innerHTML = "";
for (var product of outputTask) {
var productTwo = document.createElement("div");
productTwo.setAttribute('class', 'task');
productTwo.setAttribute('draggable', true);
var {task,member,deadline} = product;
productTwo.innerHTML =
"<div id='task'>" +
"<p>" + product.task + "</p>" +
"<ul>" +
"<li><img id='pencil-img' src='images/pencil.png' alt='task-options. Pencil'>"+
"<ul class='dropdown-menu'>" +
"<li><a href='#' onclick='deleteTask(" + product.id + ")'>Delete task</a></li>" +
"<li><a href='#' onclick='editTask(" + product.id + ")'>Edit task</a></li>" +
"</ul>"
"</li>" +
"</ul>";
outputTaskEl.appendChild(productTwo);
}
for ( i = 0; i < outputTask.length; i++){
var taskId = document.getElementsByClassName("task");
taskId[i].id = "task" + (i + 1);
}
}
And this is the drag and drop code:
function dragDropItems() {
const taskItems = document.querySelectorAll('.task');
const taskFields = document.querySelectorAll('.taskField');
for (let i = 0; i < taskItems.length; i++) {
const item = taskItems[i];
item.addEventListener('dragstart', function () {
draggedItem = item;
setTimeout(function () {
}, 0)
});
item.addEventListener('dragend', function () {
setTimeout(function () {}, 0);
})
for (let j = 0; j < taskFields.length; j ++) {
const list = taskFields[j];
draggedItem = item;
list.addEventListener('dragover', function (e) {
e.preventDefault();
});
list.addEventListener('dragenter', function (e) {
e.preventDefault();
});
list.addEventListener('drop', function (e) {
e.preventDefault();
this.append(draggedItem);
});
}
}
}
Try this:
// Save object
localStorage.setItem('key', JSON.stringify(obj))
// Get object
let obj = JSON.parse(localStorage.getItem('key'))

Javascript error after upgrade to Drupal 7

I posted a similar question at the Drupal Forum, but I haven't had much luck.
I'm upgrading a site from D6 to D7. So far it's gone well, but I'm getting a Javascript error that I just can't pin down a solution for.
This is a cut down version of the whole script:
(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
The part that keeps throwing an error I'm seeing in Firebug is at:
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
Firebug keeps stopping at "addZero is not defined". JS has never been my strong point, and I know some changes have been made in D7. I've already wrapped the entire script in "(function($) { }(jQuery));", but I must be missing something else. The same script works perfectly on the D6 site.
Here is the "fixed" version of the whole code with #Pointy suggestion added. All I left out is the part of the script for making the hash that goes to Amazon, and some of my declared variables.
(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
$(document).ready(function() {
$("#edit-field-game-title-und-0-asin").change(function() {
typedText = $("#edit-field-game-title-und-0-asin").val();
$.ajax({
type: 'POST',
data: {typedText: typedText},
dataType: 'text',
url: '/asin/autocomplete/',
success:function(){
document.getElementById('asin-lookup').style.display='none';
x = typedText.search(strSearch);
y = (x+5);
srchASIN = typedText.substr(y,10)
amazonSearch();
}
});
});
$("#search_asin").click(function() {
$("#edit-field-game-title-und-0-asin").val('');
document.getElementById('name-lookup').style.display='none';
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#edit-body").val('');
srchASIN = $("#field-asin-enter").val();
amazonSearch();
});
$("#clear_search").click(function() {
$("#field-asin-enter").val('');
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-release-dt2-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#field-amazon-platform").val('');
$("#field-amazon-esrb").val('');
$("#edit-body-und-0-value").val('');
document.getElementById('asin-lookup').style.display='';
document.getElementById('name-lookup').style.display='';
});
function amazonSearch(){
var ASIN = srchASIN;
var azScr = cel("script");
azScr.setAttribute("type", "text/javascript");
var requestUrl = invokeRequest(ASIN);
azScr.setAttribute("src", requestUrl);
document.getElementsByTagName("head").item(0).appendChild(azScr);
}
});
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var tmpItem = tmpData.Item;
}
$("#edit-title").val(tmpItem.title);
$("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
$("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-asin-und-0-asin").val(tmpItem.asin);
$("#edit-field-ean-und-0-value").val(tmpItem.ean);
$("#field-amazon-platform").val(tmpItem.platform);
$("#field-amazon-publisher").val(tmpItem.publisher);
$("#field-amazon-esrb").val(tmpItem.esrb);
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
if (obj.addEventListener){obj.addEventListener(type,fn,false);}
else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}
var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
cleanASIN = ASIN.replace(/[-' ']/g,'');
var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
var lines = unsignedUrl.split("\n");
unsignedUrl = "";
for (var i in lines) { unsignedUrl += lines[i]; }
// find host and query portions
var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
var matches = urlregex.exec(unsignedUrl);
var host = matches[1].toLowerCase();
var query = matches[2];
// split the query into its constituent parts
var pairs = query.split("&");
// remove signature if already there
// remove access key id if already present
// and replace with the one user provided above
// add timestamp if not already present
pairs = cleanupRequest(pairs);
// encode the name and value in each pair
pairs = encodeNameValuePairs(pairs);
// sort them and put them back together to get the canonical query string
pairs.sort();
var canonicalQuery = pairs.join("&");
var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
// calculate the signature
//var secret = getSecretAccessKey();
var signature = sign(secret, stringToSign);
// assemble the signed url
var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
//document.write ("<html><body><pre>REQUEST: "+signedUrl+"</pre></body></html>");
return signedUrl;
}
function encodeNameValuePairs(pairs) {
for (var i = 0; i < pairs.length; i++) {
var name = "";
var value = "";
var pair = pairs[i];
var index = pair.indexOf("=");
// take care of special cases like "&foo&", "&foo=&" and "&=foo&"
if (index == -1) {
name = pair;
} else if (index == 0) {
value = pair;
} else {
name = pair.substring(0, index);
if (index < pair.length - 1) {
value = pair.substring(index + 1);
}
}
// decode and encode to make sure we undo any incorrect encoding
name = encodeURIComponent(decodeURIComponent(name));
value = value.replace(/\+/g, "%20");
value = encodeURIComponent(decodeURIComponent(value));
pairs[i] = name + "=" + value;
}
return pairs;
}
function cleanupRequest(pairs) {
var haveTimestamp = false;
var haveAwsId = false;
var nPairs = pairs.length;
var i = 0;
while (i < nPairs) {
var p = pairs[i];
if (p.search(/^Timestamp=/) != -1) {
haveTimestamp = true;
} else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
haveAwsId = true;
} else if (p.search(/^Signature=/) != -1) {
pairs.splice(i, 1);
i--;
nPairs--;
}
i++;
}
if (!haveTimestamp) {
pairs.push("Timestamp=" + getNowTimeStamp());
}
if (!haveAwsId) {
pairs.push("AWSAccessKeyId=" + accessKeyId);
}
return pairs;
}
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
Here's a better version of your code:
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
That moves "addDate" inside the extension function, and it avoids the horrid with statement.

JS: Can not convert to object, childNodes related

Ok, feeling stupid here, but wondering what the problem is here exactly.
Although the function works as it should, I get this JS Error in Opera. Not sure about other browsers...
Uncaught exception: TypeError: Cannot
convert
'document.getElementById("shoutbox_area"
+ moduleId)' to object
oElement = document.getElementById("shoutbox_area"
+ moduleId).childNodes;
Here is the relevant code:
function appendShout(XMLDoc)
{
var shoutData = XMLDoc.getElementsByTagName("item");
var oElement = [];
if (shoutData.length > 0)
{
var moduleId = shoutData[0].getAttribute("moduleid");
if (shoutData[shoutData.length - 1].getAttribute("lastshout") != "undefined")
{
for (var i = 0; i < shoutData.length; i++)
if (shoutData[i].firstChild.nodeValue != 0)
document.getElementById("shoutbox_area" + moduleId).innerHTML += shoutData[i].firstChild.nodeValue;
oElement = document.getElementById("shoutbox_area" + moduleId).childNodes;
var i = oElement.length;
while (i--)
{
if (i % 2 == 0)
oElement[i].className = "windowbg2";
else
oElement[i].className = "windowbg";
}
oElement[oElement.length - 2].style.borderBottom = "1px black dashed";
}
}
}
Can someone please help me to understand why it is giving me an error here:
oElement = document.getElementById("shoutbox_area" + moduleId).childNodes;
Can I not assign an array to the childNodes?
EDIT:
This JS Error occurs when I try and delete a shout. The JS function for deleting a shout is this:
function removeShout(shout, moduleID)
{
var shoutContainer = shout.parentNode.parentNode;
var send_data = "id_shout=" + shout.id;
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dream;sa=shoutbox;xml;" + "delete_shout;" + "canmod=" + canMod[moduleID] + ";" + sessVar + "=" + sessId;
sendXMLDocument(url, send_data);
var shoutID = 0;
while (shoutID !== null)
{
var shoutID = document.getElementById(shout.parentNode.id);
var moduleID = shoutID.parentNode.getAttribute("moduleid");
if (shoutID.parentNode.lastChild)
{
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dream;sa=shoutbox;xml;get_shouts=" + (shoutID.parentNode.lastChild.id.replace("shout_", "") - 1) + ";membercolor=" + memberColor[moduleID] + ";maxcount=" + maxCount[moduleID] + ";shoutboxid=" + shoutboxID[moduleID] + ";textsize=" + textSize[moduleID] + ";parsebbc=" + parseBBC[moduleID] + ";moduleid=" + moduleID + ";maxcount=" + maxCount[moduleID] + ";canmod=" + canMod[moduleID] + ";" + sessVar + "=" + sessId;
getXMLDocument(url, appendShout);
}
element = shoutID.parentNode.childNodes;
var i = element.length;
while (i--)
{
if (i % 2 == 0)
element[i].className = "windowbg2";
else
element[i].className = "windowbg";
}
shoutID.parentNode.removeChild(shoutID);
}
}
Am using the following functions for the sending and getting the XMLHttpRequest as you may have noticed already in the removeShout function above:
// Load an XML document using XMLHttpRequest.
function getXMLDocument(sUrl, funcCallback)
{
if (!window.XMLHttpRequest)
return null;
var oMyDoc = new XMLHttpRequest();
var bAsync = typeof(funcCallback) != 'undefined';
var oCaller = this;
if (bAsync)
{
oMyDoc.onreadystatechange = function () {
if (oMyDoc.readyState != 4)
return;
if (oMyDoc.responseXML != null && oMyDoc.status == 200)
{
if (funcCallback.call)
{
funcCallback.call(oCaller, oMyDoc.responseXML);
}
// A primitive substitute for the call method to support IE 5.0.
else
{
oCaller.tmpMethod = funcCallback;
oCaller.tmpMethod(oMyDoc.responseXML);
delete oCaller.tmpMethod;
}
}
};
}
oMyDoc.open('GET', sUrl, bAsync);
oMyDoc.send(null);
return oMyDoc;
}
// Send a post form to the server using XMLHttpRequest.
function sendXMLDocument(sUrl, sContent, funcCallback)
{
if (!window.XMLHttpRequest)
return false;
var oSendDoc = new window.XMLHttpRequest();
var oCaller = this;
if (typeof(funcCallback) != 'undefined')
{
oSendDoc.onreadystatechange = function () {
if (oSendDoc.readyState != 4)
return;
if (oSendDoc.responseXML != null && oSendDoc.status == 200)
funcCallback.call(oCaller, oSendDoc.responseXML);
else
funcCallback.call(oCaller, false);
};
}
oSendDoc.open('POST', sUrl, true);
if ('setRequestHeader' in oSendDoc)
oSendDoc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
oSendDoc.send(sContent);
return true;
}
Hopefully this is good enough, you can do a view source on it to see the actual HTML, but there are attributes that get added to the Shoutbox tags at runtime so as to be XHTML compliant, etc..
Please let me know if there is anything else you need?
Thanks :)
The code is breaking because shoutID is null in the second of these two lines, the second time through the loop:
var shoutID = document.getElementById(shout.parentNode.id);
var moduleID = shoutID.parentNode.getAttribute("moduleid");
The first of those lines is strange. Why not just use var shoutID = shout.parentNode;?
Also, the moduleId attribute seems to be nowhere around.
What are you trying to achieve with the while loop?

Categories