Titanium passing data to createHTTPClient - javascript

I have a loop that parses a JSON from a request, and generates a table.
Now the images on that table need to be downloaded, which is why i use a createHTTPClient request to get the images.
The issue is, i want to update the rows live as the image is downloaded.
But due to createHTTPClient being async, it fails to do that... It always gets the last row...
How do i pass the current row to the onload event?
My code goes something like:
onload: function(e) {
asjson = JSON.parse(this.responseText);
for (var i=0;i<asjson.objects.length;i++){
var fname = asjson['objects'][i].photos[0].photo;
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, fname);
var row = Ti.UI.createTableViewRow({
title : asjson['objects'][i].name,
hasChild : true,
color: 'white',
albumid : asjson['objects'][i].id,
songid : asjson['objects'][i].id,
id : asjson['objects'][i].staff[0].id,
idtype : 1
});
if (!file.exists()) {
var c = Titanium.Network.createHTTPClient();
c.setTimeout(10000);
c.open('GET','http://localhost:8000/' + fname);
c.file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, fname);
c.onload = function(e){
file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, fname);
row.leftImage = f1 = Titanium.Filesystem.applicationDataDirectory + '/' + fname;
};
c.send();
}
}

So you have a couple of different options here. You could create all the rows ahead of time. Then once the images are loaded, loop over the table looking for the correct row and setting the images then.
However I would recommend the following approach. The JSLint website has a good explanation why adding functions is a bad idea inside of a loop. JSLint
onload: function(e){
var asJson = JSON.parse(this.responseText);
for(var i = 0, length = asJson.objects.length; i < length; i++){
var fileName = asjson.objects[i].photos[0].photo;
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, fileName);
var fileId = asJson.objects[i].id;
var row = Ti.UI.createTableViewRow({
title : asJson.objects[i].name,
hasChild : true,
color: 'white',
albumid : fileId,
songid : fileId,
id : asJson.objects[i].staff[0].id,
idtype : 1
});
if(!file.exists()){
var c = Titanium.Network.createHTTPClient();
c.setTimeout(10000);
c.open('GET','http://localhost:8000/' + fileName);
c.file = Titanium.Filesystem.getFile(Titanium.FileSystem.applicationDataDirectory,fileName);
c.onload = rowImageOnLoadHandler(row,fileName);
c.send();
}
}
}
Notice the rowOnLoadHandler function. This function will allow you to keep a reference to the row the HTTPClient request is running for.
function rowImageOnLoadHandler(row,fileName){
return function(){
row.leftImage = Titanium.Filesystem.applicationDataDirectory + '/' + fileName;
};
}

So i got creative and came up with another answer.
Basically, i append the row number to the url:
c.open('GET','http://localhost:8000/' + fileName + '?i=' + i);
Then, i can access the location property by using this.location.
From there on, it's a matter of updating the row with the data...

Related

Is there a JavaScript InDesign function to get ID value

I used the command to export the hard drive ID to drive C:
var command="wmic diskdrive get SerialNumber > C:/idhdd.txt";
app.system("cmd.exe /c\""+command+"" );
I get the text file
SerialNumber
2012062914345300
Is there a JavaScript statement to remove SerialNumber, I just want to get the ID in the text file and save it to the hard drive C.
Here's ready-to-use getDriveIDs() function that should work in any Adobe app and will return array of HDD ID strings for you. I hope this can be easily generalized for other scenarios with Windows scripting inside Adobe scripting ;-)
//----------------------------------------------------------------------//
// Detects IDs (serial numbers) of connected drives and returns them as array of strings.
var getDriveIDs = function() {
var idFile = File(Folder.temp + '/saved_hdd_serials.txt');
var scriptFile = File(Folder.temp + '/dump_hdd_serials.bat');
var scriptContent = 'wmic diskdrive get SerialNumber > ' + idFile.fsName + '\n';
var ids = []
withTempFile(scriptFile, scriptContent, function() {
scriptFile.execute();
$.writeln(idFile.length == 0); // wait for asynchronous script execution to finish
$.sleep(1);
withTempFile(idFile, undefined, function(file, lines) {
ids = lines.slice(1);
});
});
return ids;
};
//----------------------------------------------------------------------//
// utilities
var withTempFile = function(file, content, callback) {
if (undefined == content) { // read temp file
file.open('r');
content = [];
while (!file.eof)
content.push(file.readln());
} else { // write temp file
file.open('w');
file.write(content);
content = undefined;
}
file.close();
callback(file, content);
file.remove();
}
//----------------------------------------------------------------------//
// main: demo
var ids = getDriveIDs();
alert('Drive IDs:\n\t' + ids.join('\n\t'));

How convert template HTML with images to PDF in ServiceNow?

I need to create dynamic pdf with html templates in servicenow, but my problem is that these pdf must contain images and styles, and I have not been able to solve it.
try using the api of GeneralPDF of servicenow and get the template converted to pdf but only when it contains text. when I put images I get the following error:
This error appears to me when executing my code:
ExceptionConverter: java.io.IOException: The document has no pages.:
org.mozilla.javascript.JavaScriptException: ExceptionConverter:
java.io.IOException: The document has no pages.:
this is in a script include and is called from UI Action
my code to convert the html to pdf is the following:
create : function (sys_id){
var carta = new GlideRecord('x_solsa_casos_plant_doc');
carta.addQuery('sys_id','6f1e4ac8db29f300ab7c0f95ca96197a');
carta.query();
if(carta.next()){
var parsedBody = carta.body;
var gr = new GlideRecord('x_solsa_casos_x_solsa_casos');
gr.get('sys_id',sys_id);
var sampleString=parsedBody.toString();
var reg = new SNC.Regex('/\\$\\{(.*?)\\}/i');
var match = reg.match(sampleString);
var count =0;
var variables = [];
var values = [];
var tmpValue;
while (match != null)
{
variables.push(match.toString().substring(match.toString().indexOf(',')+1));
match = reg.match();
values.push(variables[count]);
gs.log("array values : " + values);
if(gr.getDisplayValue(values[count])==null || JSUtil.nil(gr.getDisplayValue(values[count])))
{
tmpValue='';
}else{
tmpValue=gr.getDisplayValue(values[count]);
gs.log("tmpValue :" +tmpValue);
}
parsedBody = parsedBody.replace('${'+variables[count]+'}', tmpValue);
count++;
gs.log("parsedBody : " + parsedBody);
}
this.createPDF(parsedBody,'x_solsa_casos_x_solsa_casos',sys_id,'carta.pdf');
}
},
createPDF : function(html, table, sys_id, filename) {
var pdfDoc = new GeneralPDF.Document(null, null, null, null, null, null);
this._document = new GeneralPDF(pdfDoc);
this._document.startHTMLParser();
this._document.addHTML(html);
this._document.stopHTMLParser();
this.saveAs(table, sys_id, filename);
},
saveAs : function (table, sys_id, filename){
var att = new GeneralPDF.Attachment();
att.setTableName(table);
att.setTableId(sys_id);
att.setName(filename);
att.setType('application/pdf');
att.setBody(this._document.get());
GeneralPDF.attach(att);
},
Looks like parsedBody is empty or doesn't always contain HTML. According to this answer, paseXHtml (which ServiceNow probably uses and should be in the complete stack trace) expects HTML tags, not just text:
https://stackoverflow.com/a/20902124/2157581

How do I get $.getJSON to work on JSONP

I know it looks like a lot but my question pertains to a single line of (bolded) code. I know my event handler is set up correctly. I know my url is what it should be by this point, except for the ?callback=? part (I read in another post that by putting this at the end of the url passed to $.getJSON, the getJSON becomes capable of working with JSONP, and according to their API page wiki uses JSONP). I also know for certain that the domMod function NEVER RUNS, NOT EVEN THE FIRST LINE OF IT. So don't worry about the other parts of my code, just please if you can tell me why my $.getJSON is not calling the function, I am really new to this stuff. The error message I get back is
wikiViewer.html:1 Refused to execute script from
'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=searc…=jordan?callback=jQuery111107644474213011563_1454965359373&_=1454965359374'
because its MIME type ('application/json') is not executable, and
strict MIME type checking is enabled.
(function(){
var searchBtn = document.getElementById('search');
//var body = document.getElementsByTagName('body')[0];
var input = document.getElementById("input");
var bodyDiv = document.getElementById('bodyDiv')
$(document).ready(function(){
searchBtn.addEventListener('click', searchWiki);
function searchWiki(){
bodyDiv.innerHTML = "";
var url = 'https:\/\/en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch='
if (input.value === ""){
return;
}
var searchTerm = input.value.replace(/\s/g, '%20');
url = url + searchTerm + "?callback=?";
**$.getJSON(url, domMod)** //change fileName to be whatever we wish to search
function domMod(json){ //what to do with dom based on json file NOTE WE NEED TO FIRST CHECK ANDREMOVE PREVIOUS SEARCH CONTENT
var entry;
if (!json.hasOwnProperty(query)){
return;
}
if (!json.query.hasOwnProperty(pages)){
return;
}
json = json.query.pages;
var keys = Object.keys(json);
var keysLength = keys.length;
for (var i = 0; i < keysLength; i++){
entry = json[keys[i]];
var outterDiv = document.createElement('div');
outterDiv.className = "entry";
var imageDiv = document.createElement('div');
imageDiv.className = "entryImg";
var entryDiv = document.createElement('div');
entryDiv.className = "entryTxt";
outterDiv.appendChild(imageDiv);
outterDiv.appendChild(entryDiv);
entryDiv.innerHTML = '<h2>' + entry.title + '</h2>' + '<p>' + entry.extract + '</p>'
if (entry.hasOwnProperty('thumbnail')){ //add image to our imageDiv child of entryDiv
imageDiv.style.backgroundImage = "url('" + entry.thumbnail.source + "')"
}
bodyDiv.appendChild(outterDiv); //appendChild to the Body
}
}
}
});
}())
You already have a query string started in url using ? but are adding another ? when you do:
url = url + searchTerm + "?callback=?";
Change to
url = url + searchTerm + "&callback=?";
Works fine when I sent term "food"
DEMO

Get String Value of Blob Passed to e.parameter in Apps Script

I'm using this code to get a blob passed to a function:
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
This is the error I get:
Execution failed: TypeError: Can not find getDataAsString function in
the Blob object.'arrayBlob'
How do I get the string value of this blob?
Here is my code:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = userProperties.getProperty('savedArray');
arrayList = JSON.stringify(arrayList);
var arrayBlob = Utilities.newBlob(arrayList);
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
arrayList = JSON.parse(arrayList);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
I'd like the solution worked with more than one user simultaneous using the script.
Update:
Add a global variable OUTSIDE of any function:
var arrayBlob = Utilities.newBlob("dummy data");
function showList(folderID) {
Code here ....
};
Check that the code has access to the blob:
function submit(e){
Logger.log("arrayBlob.getDataAsString(): " + arrayBlob.getDataAsString());
//More Code . . .
}
This solution eliminates the need of embedding a hidden element in the dialog box with a value of the blob.
You won't need this line:
panel.add(app.createHidden('arrayBlob', arrayBlob));
There are other changes I'd make to the code, but I simply want to show the main issue.
Old Info:
In the function showList(), the method getDataAsString() works on the blob named arrayBlob.
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
In the function, submit(), the same method does not work.
var arrayBlob = e.parameter.arrayBlob;
In the function showList(), the code is assigning a newBlob to the variable arrayBlob. So arrayBlob is available to have the getDataAsString() method used on it.
var arrayBlob = Utilities.newBlob(arrayList);
In the function, submit(), you are trying to pass the arrayBlob blob variable into the submit() function, and reference it with e.parameter.
If you put a Logger.log() statement in the submit() function.
function submit(e){
Logger.log('e: ' + e);
Logger.log('e.parameter` + e.parameter);
var arrayBlob = e.parameter.arrayBlob;
Those Logger.log statements should show something in them. If there is nothing in e.parameter, then there is nothing for the .getDataAsString() to work on.
It looks like you are putting the arrayBlob into a hidden panel.
panel.add(app.createHidden('arrayBlob', arrayBlob));
But when the object is getting passed to the submit(e) function, the arrayBlob might not be getting put into that object.
So, what I'm saying is, the:
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
Line may be perfectly good, but there is no arrayBlob there to work on. This hasn't fixed your problem, but do you think I'm understanding part of what is going on?
I'm not sure why you are using Blob's here at all, you could simply work with JSON instead.
However, if you have a reason to use Blobs, you can pass the JSON data through your form and create the Blob in your handler, as the modified code below does:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = UserProperties.getProperty('savedArray');
//get JSON data pass through form.
var arrayBlob = JSON.stringify(arrayList);
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
//include JSON Data in the form.
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = Utilities.newBlob(e.parameter.arrayBlob);
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
In the method you were using originally, the Blob itself was never included in the form, you were simply passing the string "Blob" around.
This is because the function createHidden(name, value); expects two strings as parameters, so it calls ".toString()" on the arrayBlob object, which returns the string "Blob".

FF Extension - Not Keeping Global Variable Values

I'm working on a FF extension that in short, loads dynamic images into a sidebar. The ID's that I get are from a JSON response, and are stored in a global variable declared in the same .js file as I intend to use it. My problem is when I try to simulate paging through my results. I load the sidebar using my global variable and everything is ok. When I try to then move on to the next set of images to display using the ID's i've stored in my global variable it failes due to my variable having been completely reset. I'll see if I can give a rough view of my code:
var searchVars = {
'keyword': "",
'totalResults': 0,
'imgIds': [],
'cIds': [],
'curPg': "1",
'dispStartIdx': 0,
'dispEndIdx': 4,
'dispPerPg': 5,
toString: function() {
return this.keyword + ", " +
this.totalResults + ", " +
this.imgIds + ", " +
this.cIds + ", " +
this.curPg + ", " +
this.dispStartIdx + ", " +
this.dispEndIdx + ", " +
this.dispPerPg;
}
};
var corbisquicksearch = {
onSearch: function () {
cqsearch.resetSearch(); //Resets my global variable every search
searchVars.keyword = cqsearch.getSelectedText(); //searchVars is my global variable im having trouble with
cqsearch.extendImageCache();
}
extendImageCache: function() {
var postToURL = 'http://www.agenericurl.com/Search?';
var keyword = searchVars.keyword;
var p = 1; //Page Offset for ID's returned
var size = 200; //Number of ID's returned in the response set
var query = "searchQuery=" + encodeURIComponent("q=" + keyword + "&p= " + p +"&s=" + size);
var request = new XMLHttpRequest();
request.open('post', postToURL + query, true);
request.onreadystatechange = function (aEvt) {
if (request.readyState == 4) {
alert(1);
if(request.status == 200) {
alert(2);
var responseInJSON = JSON.parse(request.responseText);
searchVars.totalResults = responseInJSON.ResultsCount;
var i = searchVars.imgIds.length;
var lastResult = i + responseInJSON.SearchResultImages.length;
while (i < lastResult) {
searchVars.imgIds[i] = responseInJSON.SearchResultImages[i].ImageId;
searchVars.cIds[i] = responseInJSON.SearchResultImages[i].CorbisId;
i++;
}
cqsearch.loadSidebar();
}
else {
dump("Error loading page\n");
}
}
};
request.send();
},
loadSidebar: function() {
//Initializing Env Variables
var sidebar = document.getElementById("sidebar");
var sidebarDoc = sidebar.contentDocument || document;
var searchInfoBox = sidebarDoc.getElementById("search_info");
var resultsBox = sidebarDoc.getElementById("img_results");
var pagingInfoBox = sidebarDoc.getElementById("paging_info");
//Loading up the search information
var searchInfo = "Displaying Results for <b>{0}<b/><br>Showing <b>{1} - {2}</b> of <b>{3}</b>";
var args = [searchVars.keyword, searchVars.dispStartIdx, searchVars.dispEndIdx, searchVars.totalResults];
var infoLbl = document.createElement("label");
infoLbl.setAttribute("value", cqsearch.strFormat(searchInfo, args));
searchInfoBox.appendChild(infoLbl);
while (resultsBox.firstChild) {
resultsBox.removeChild(resultsBox.firstChild);
}
//Loading up the image results
var i = searchVars.dispPerPg * (searchVars.curPg - 1);
var lastDisplayed = (searchVars.curPg * searchVars.dispPerPg) - 1;
alert("length" + searchVars.toString());
while (i <= lastDisplayed) {
var imageID = searchVars.imgIds[i];
var cID = searchVars.cIds[i];
var imgSrc = cqsearch.createMediaUrlParams(imageID, 'thumb', cID, false).url; //thumb, 170, hover
var img = document.createElement("image");
img.setAttribute("src", imgSrc);
alert(imgSrc);
img.setAttribute("class", "img");
var idDelimiter = "_image";
var id = cID + idDelimiter;
img.id = id;
img.addEventListener("click", function () {
cqsearch.openEnlargementPage(this.id.substring(0, this.id.indexOf(idDelimiter)));
}, false);
var imgBox = document.createElement("box");
imgBox.setAttribute("class", "imgContainer");
imgBox.appendChild(img);
resultsBox.appendChild(imgBox);
i++;
}
//Loading up paging info and functionality
var prevBtn = document.createElement("button");
prevBtn.setAttribute("label", "Previous");
prevBtn.setAttribute("oncommand", "cqsearch.prevPage()");
var nextBtn = document.createElement("button");
nextBtn.setAttribute("label", "Next");
nextBtn.setAttribute("oncommand", "cqsearch.nextPage()");
pagingInfoBox.appendChild(prevBtn);
pagingInfoBox.appendChild(nextBtn);
},
nextPage: function() {
searchVars.curPg++;
alert(searchVars.imgIds);
cqsearch.loadSidebar();
},
};
I realize its a lot of code, and I didn't post every function I have, and no, this specific URL does not work. Everything not included works fine, and does exactly what its supposed too, and nothing more which is why I left it out. But if anyone could shed some light on why my global variable is being cleared between my initial load of the sidebar, and when I click to go to the next page, I would greatly appreciate it.
If you need me to add something or clarify something please let me know and I will do so! I will probably end up sliming this code down and removing irrelevant parts.
Thanks!
If you simply want a place to store some global variables for a session, then a JavaScript Module would probably work.
Would you be able to use the client side storage to store the global variable? you will then, not lose it on page loads or refresh. You could either use this to debug and see if you are getting a page refresh because sometimes extensions are fickle and you don't even notice the refresh, but if you store the variable as a key value pair in web storage you might get past this.
localStorage.setItem('imgId', '5');
to set your key/value pair
localStorage.getItem('imgId');
to retrieve your key/value pair
Then you can set a new local storage for each series of pictures that has been displayed to the client based on the last number that is set in local storage.

Categories

Resources