To give you a brief understanding on what I am trying to accomplish. I have an HTML which is dynamically generated. I need to convert that HTML into a specific JSON format. I have the code here in JSFiddle.
[link]: http://jsfiddle.net/X3p47/2/
function walk(node, result) {
var pages = jQuery("[data-role='page']");
pages.each(function () {
var obj = {};
console.log("Inside");
obj.text = $(this).attr('id');
obj.isFolder = true;
obj.isExpanded = true;
obj.children = findChild(this);
result.push(obj);
});
//This is how I am calling the walk function
var a = [];
var testVal = localStorage.getItem( 'htmlValue' );
walk($.parseHTML(testVal), a);
console.log(JSON.stringify(a));
The code works fine and all, but the problem is that when I deploy the javascript (the above mentioned one) in my jsp page(name of my jsp page is dataMapping.jsp) it's taking the HTML of dataMapping rather than the HTML which I am supplying. If anyone could give me some inputs would be greatly appreciated.
The part where you see var pages = jQuery("[data-role='page']"); is basically becoming null, because it's taking the html of my page which is dataMapping.jsp
Try making this modification to your code. Rather than pages.each(function) try this
$each.(node, function(){
Related
I'm trying to write a little script to make my coworkers and mine lives easier. I am trying to append lines to a spreadsheet based on information entered into a custom form. The code posted below just the doPost block which should be appending the google spreadsheet.
function doPost(form) {
var PN = form.PartNumber;
var REV = form.Revision;
var DATE = form.RevisionDate;
var DESC = form.Description;
var NOTE = form.PartNotes;
var URL = form.myFile.getURL();
var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
var sheet = ss.getSheetName('Uploads');
sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}
I am unsure why it isn't writing to the spreadsheet but it isn't throwing me any errors. If you can offer any insight as to what is wrong I would greatly appreciate it; there are many guides online but most seem to be based on deprecated functions/code/etc.
Thanks for your time.
Instead of using doPost, set up a "On form submit" trigger.
You need to get the namedValues to be able to pull specific values and take the first output.
Also, it should be "getSheetByName('Uploads')" .
As pointed out in the previous answer, it is unclear what you are trying to achieve by "form.myFile.getURL();" If you want to get the form url you might as well create it as a string, as it always stays the same.
Here is a working example of your code:
function doPost(form) {
var formResponses = form.namedValues;
var PN = formResponses.PartNumber[0];
var REV = formResponses.Revision[0];
var DATE = formResponses.RevisionDate[0];
var DESC = formResponses.Description[0];
var NOTE = formResponses.PartNotes[0];
//var URL = form.myFile.getURL(); //Not sure what you are tyring to get here as form URL will always be the same.
var URL = "Your form's url"; //You can put the form url in here so it will be pushed in to every row.
var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
var sheet = ss.getSheetByName('Uploads');
sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}
The form fields are nested in a "parameter" property in the doPost parameter.
So, you should access them using:
function doPost(form) {
var actualForm = form.parameter;
var PN = actualForm.PartNumber;
//etc
To double check all parameters your receiving and their names, you could append to your sheet everything stringfied, like this:
sheet.appendRow([JSON.stringify(form)]);
--edit
This form.myFile.getURL() also looks odd. I guess another good debugging trick you could do is to wrap everything in a try-catch and email yourself any errors you get. For example:
function doPost(form) {
try {
//all your code
} catch(err) {
MailApp.sendMail('yourself#etc', 'doPost error', err+'\n\n'+JSON.stringify(form));
}
}
On form submit
onFormSubmit works. "doPost" looks wrong.
Simple example:
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
Full example - Scroll down to the code http://www.labnol.org/internet/google-docs-email-form/20884/ (Note: example sends email)
Trigger docs: https://developers.google.com/apps-script/guides/triggers/events
Notes: I think the problem is doPost, Does it work with google Forms? Never seen it used with google forms.
First and foremost, thank you everyone who has responded with information thus far. None of the solutions posted here worked for my particular implementation (my implementation is probably to blame, it is very crude), but they definitely set me down the path to a working version of my form which we now lightly use. I have posted some of the code below:
function sheetFill(form, link) {
try {
var formResponses = form.namedValues;
var toForm = [0,0,0,0,0,0,0];
for (i=0;i < form.PartNumber.length;i++){
toForm[0] = toForm[0]+form.PartNumber[i];
}
... (several for loops later)
var d = new Date();
var ss = SpreadsheetApp.openById("IDHERE");
var sheet = ss.getCurrentSheet;
ss.appendRow([toForm[0], toForm[1], toForm[2], toForm[3], toForm[4], toForm[5], toForm[6], link, d]);
} catch(err) {
MailApp.sendEmail('EMAIL', 'doPost error', err+'\n\n'+JSON.stringify(form));
}
}
It is not very versatile or robust and isn't elegant, but it is a starting point.
So with the code below I am able to get the information shown below e.g. streamTitle.
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName)), true);
if ($json_array['stream'] != null) {
$currentGame = $json_array['stream']['channel']['game'];
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$viewers = $json_array['stream']['viewers'];
}
But what I want to do is to get what comes after self: e.g.(https://api.twitch.tv/kraken/streams/woohaa666) of an API response like the one below which has a specified game and limit, but I'm not sure how to do so. I tried something similar to the code above $channelurlAPI = $json_array['streams']['self'], but it displays nothing.
https://api.twitch.tv/kraken/streams?game=Diablo+III&limit=1
Im not sure how much this will help you but i was doing work with the twitch API a few months ago I found it very hard but was able to get game searches working and to bring in streams
hope it helps here is the code that i used
//Twitch Streams //Ref: https://github.com/justintv/Twitch-API/blob/master/embedding.md
function getTwitch(title){
$.getJSON("https://api.twitch.tv/kraken/search/streams?q="+title+"&limit=20&type=top&callback=?", function (data) {
var temp = "";
$.each(data.streams.slice(0,5), function (index, item) {
temp = temp + "<a target='frame1' href='http://www.twitch.tv/widgets/live_embed_player.swf?channel=" + item.channel.name + "'><button>"+item.channel.display_name+"</button></a><br />";
});
$("#StreamList").html(temp);
});
}
Here is a sample jsfiddle i build using the original api code that u my use as a jumping of point aswell but the code above is the final code I used
http://jsfiddle.net/F4tsM/10/
You should try
$json_array['_links']['self']
Our application currently shares messages between the Java and Javascript side. They are stored as resource bundles in the class path, and we have a custom controller that returns all the messages as Json. The client side code look like this:
// This calls the controller to get all the messages
var messages = MessageBundle();
var text = messages.get('my.message', 1);
This is great because we can mock "messages" in our unit tests.
I want to start using JAWR for this, since we already use it for other things. The problem is JAWR generates the following Javascript object:
var text = messages.my.message(1);
This means the code cannot be unit tested anymore unless the unit tests also define a global "messages" variable with the right nested objects. Is there a way around this? Any idea how to extend JAWR to make this unit-testable?
Currently my work around is:
function messages() {
var args = Array.prototype.slice.call(arguments);
var messageId = args.shift();
var messageFunc = window.messages;
messageId.split('.').forEach(function(part) {
messageFunc = messageFunc[part];
});
return messageFunc(args);
}
// Same syntax as the old one, but uses the JAWR object behind the scenes
// This function is easy to mock for a unit test
var text = messages('my.message', 1);
Thanks for any ideas!
Maybe next samples can help you.
1)
function messagesTester(funcPath,id) {
var args=funcPath.split('.'),root=window.messages;
for(var i=0;i<args.length;i++)root=root[args[i]];
return root(id);
// or if more that one parameter for *func*, then, for example:
// return root.apply(null,Array.prototype.slice(arguments,1));
}
var text = messagesTester('my.message',1);
2)
function messagesTester(funcPath) {
var args=funcPath.split('.'),root=window.messages;
for(var i=0;i<args.length;i++)root=root[args[i]];
return root;
}
// var text = messagesTester('my.message')( /*arguments list*/ );
var text = messagesTester('my.message')(1);
I've got a webpage which reads an XML file and loads the contents into a div on the page. As a part of this process, I need to identify all of the namespace prefixes and corresponding URIs declared in that file. I'm using jQuery to get and load the file like this:
$.get(sourceURI, function (data) {
var nsList = getNamespaces(data);
var target = $('#my_div');
target.html(data);
});
where getNamespaces is a function taking the result of the get, and returning an object in the form:
object = {
prefix1: uri1, //e.g xmlns:foo="http://bar.com" -> { foo: "http://bar.com" }
prefix2: uri2,
....
prefixn: urin
}
I have a sinking feeling that the answer may be a regex, but obviously that requires me to write one, and suffer over-used adages about having two problems from my colleagues. Is there a better way, or if not could someone point me in the right direction in constructing a regex?
Thanks!
If your browser is XHTML-compliant, you can use its parsing facilities to iterate over the XML elements with jQuery instead of processing a raw string with regular expressions:
function getNamespaces(data)
{
var result = {};
$(data).each(function() {
recurseGetNamespaces(this, result);
});
return result;
}
function recurseGetNamespaces(element, result)
{
var attributes = element.attributes;
for (var i = 0; i < attributes.length; ++i) {
var attr = attributes[i];
if (attr.name.indexOf("xmlns:") == 0) {
var prefix = attr.name.substr(6);
if (!(prefix in result)) {
result[prefix] = attr.value;
}
}
}
$(element).children().each(function() {
recurseGetNamespaces(this, result);
});
}
You can find a fiddle demonstrating this method here. (Disclaimer: that fiddle uses JSON.stringify() to display the results, so that part of the code might not work with browsers other than Firefox).
Does anyone have experience with Pushlets?
I have been working on it several days. I can make it work on regular javascript, but when I add HTML canvas and use javascript to draw something based on the "push"ed data, it doesn't work.
In my simple example:
document.getElementById('sometag').innerHTML = event.get("x");
document.getElementById('sometag').innerHTML = event.get("x");
...
document.getElementById('sometag').innerHTML = event.get("x");
if I keep all these regular tag there is no problem, but when I add:
document.getElementById('canvas').getContext('2d').fillRect(....);
it doesn't work. The error says can not receive XML data.
So any help? Thanks in advance.
You probably need to evaluate scripts in HTML pushed from server. Something like this:
function extractScripts(html) {
// based on PrototypeJs
var ScriptFragment = "<script[^>]*>([\\S\\s]*?)<\/script>";
var matchAll = new RegExp(ScriptFragment, "img");
var matchOne = new RegExp(ScriptFragment, "im");
return (html.match(matchAll) || []).map(function(scriptTag) {
return (scriptTag.match(matchOne) || ['', ''])[1];
});
}
function evalScripts(html) {
return extractScripts(html).map(function(script) { return eval(script) });
}