Parsing XML data using google script - javascript

I have been trying to convert a xml feed into human readable form but have not succeeded . I have tried seeing the example given in tutorails section but its too complex. Please can someone help me out with what is to be done. I can do fine till parsing of xml.
I am using google script and the output has to be in google docs.
here is what i came up with till now
var response = UrlFetchApp.fetch("http://getRecords.php?oauth_token=3e73c7&lat="+lat+"&lon="+lon+"&searchFor="+text+"&miles=100&response_type=xml");
var doc = Xml.parse(response.getContentText(), true)
var root = doc.getElement();
var entryList = "<ul>\n";
var entries = root.getElements("details");
for (var i=0; i<entries.length; i++) {
var e = entries[i];
var name = e.getElement("name").getText();
}
entryList += "<li>name </li>" + name;
entryList += "</ul>\n";
return entryList;
Here is the xml
<record>
<details>
<id>212929</id>
<distance>0</distance>
<category cat="8" sub="202" id="1201">General</category>
<name>Text Book Center</name>
<short_desc>One of Kenya's finest</short_desc>
<long_desc>
One of Kenya's leading bookshops, the Text Book Center offers a wide selection of titles. There is everything here from textbooks to fiction to the latest Information Technology titles. The range of maps is especially impressive. The shop is spacious and cool, giving shoppers plenty of room to browse the shelves upon shelves of books. Look out for the regular special offers.
</long_desc>
<address>
<address1>Kijabe Street</address1>
<city>Nairobi</city>
<country>Kenya</country>
<latitude>0</latitude>
<longitude>0</longitude>
</address>
<neighborhood>Downtown</neighborhood>
<phone>+254 2 330 340</phone>
<email>info#tbc.co.ke</email>
<open_hours>8am-1pm; 2pm-5.30pm Mon-Sat.</open_hours>
</details>
</record>
</records>
how do i remove the tags and just print it out in docs. Please help
thanks

Looks root node opening tag is missing. Is it original doc? or just paste error?
Try like this
var response = UrlFetchApp.fetch("http://getRecords.php? oauth_token=3e73c7&lat="+lat+"&lon="+lon+"&searchFor="+text+"&miles=100&response_type=xml");
var doc = Xml.parse(response.getContentText(), true);
var records = doc.records.getElements("record");
var entryList = "<ul>\n";
for (var i=0; i < records.length; i++) {
var details = records[i].details;
var name = details.name.getText();
entryList += "<li>" + name + "</li>\n";
}
entryList += "</ul>\n";
return entryList;

Related

Copy a variable from the console to the clipboard

I created a spreadsheet to keep track of all the videos uploaded by the YouTubers I follow. Then, I created a script to be executed from the console that lists all the videos of that user. I store the list in a variable, and then I log it, select it, and copy it to the clipboard, but I'd like to copy it automatically every time I run the script. The problem is that the text is not inside an element (like a div, or textarea), so I can't use either window.navigator.clipboard or document.execCommand('copy').
Is there a way to do that?.
Thanks & greets from Argentina (Hope it is from England someday).
IDsign4U (Marcelo Miguel Bazan).
This is the code I use (open the videos tab in any channel and try it):
console.clear();
console.log("Título + Duración + Estado + URL en Subscripciones (sin número de orden)");
var domains = "";
var i = "";
var text = "";
var title = "";
var duration = "";
var hours = "";
var link = "";
var video = "";
var textDuration = "";
var hoursCheck = "";
var finalDuration = "";
var finalTitle = "";
domains = document.getElementsByTagName('ytd-grid-video-renderer')
for (i = 0; i < domains.length; i++)
{title = domains[i].getElementsByTagName('h3');
duration = domains[i].getElementsByTagName('span');
link = domains[i].getElementsByTagName('a');
textDuration = duration[0].innerText.trim();
hoursCheck = "";
hoursCheck = textDuration.length > 5 ? "0": "00:";
finalDuration = hoursCheck + textDuration + "\t" + "P" + "\t";
finalTitle = title[0].innerText + "\t";
url = "https://www.youtube.com" + link[0].attributes['href'].value;
video = video + finalTitle + finalDuration + url + "\n";}
console.log(video);
Why shouldn't you be able to use navigator.clipboard? It works fine while providing variables to copy to clipboard.
document.getElementById("copy").addEventListener("click", async () => {
const text = "Text copied to the clipboard"
await navigator.clipboard.write(text)
})
<button id="copy">
Copy to clipboard
</button>
When you say "from the console", do you mean the browser console? If so, there's a built-in global copy function (not window.copy, just copy).
Yes!! Thank you Zac (and wOxxOm and Jannis Ioannou) for the answer.
It's just a matter of deleting the, for me, weird DOM element with the ID 'copy' to be able to use the copy function in the console.
Thanks & greets from Argentina (Hope it is from England someday).
IDsign4U (Marcelo Miguel Bazan).

text string output stops after first space, js/html

I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>

Use Script and XML Feed to pause Adgroups in Google Adwords

I'm trying to do a script which pauses an adgroup based in the field AVAILABILITY in a XML (a Google Merchant XML).
I have a merchant XML, and want to use the ID (the id is algo used in the adgroup name) and AVAILABILITY (In Stock, Out of Stock, Preorder) from the XML to pause Adgroups in my campaign.
I tried to modify an example, I had found here, using adgroups in place of campaigns, but I think the error is when the script try to read the XML.
In the lines bellow lines I receive the error: "TypeError: Cannot call method "getValue" of null. (line 16)"
var id = entries[i].getChild('g:id').getValue();
var availability = entries[i].getChild('g:availability').getValue();
My XML is like this:
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<item>
<title>
<![CDATA[ Far Cry 4: Overrun ]]>
</title>
<link>https://www.nuuvem.com/item/far-cry-4-overrun</link>
<description>
<![CDATA[
Neste novo conteúdo para Far Cry 4, enquanto a guerra sem trégua por Kyrat continua, os jogadores assumirão o papel dos Rakshasa e do Caminho Dourado para manter locais que dão pontos no mapa da batalha.
]]>
</description>
<g:availability>in stock</g:availability>
<g:price currency="BRL">8.99</g:price>
<g:image_link> http://dskhvldhwok3h.cloudfront.net/image/upload/t_boxshot_big/v1/products/557dbcb269702d0a9c490801/boxshots/ynhjodwlnmur0crkiaxp.jpg </g:image_link>
<g:product_type>
<![CDATA[ Ação ]]>
</g:product_type>
<g:google_product_category>Software > Video Game Software > Computer Games</g:google_product_category>
<g:condition>new</g:condition>
<g:identifier_exists>FALSE</g:identifier_exists>
<g:id>2668</g:id>
</item>
My script now looks like this:
function main() {
// Load an XML file:
var xmlURL = "XML URL HERE";
var xmlFile = UrlFetchApp.fetch(xmlURL);
// Parse the XML file:
var document = XmlService.parse(xmlFile);
var root = document.getRootElement();
// Go through all children of <deepdive_pages>:
var entries = document.getRootElement().getChildren();
for (var i = 0; i < entries.length; i++) {
//for (var i = 0; i < 10; i++) {
var id = entries[i].getChild('g:id').getValue();
var availability = entries[i].getChild('g:availability').getValue();
// If company_root_id has 0 jobs
if (availability == "out of stock") {
var adGroupIterator = AdWordsApp.adGroups().withCondition('Name CONTAINS "| ' + id + ' |"').get(); // Find all campaigns with the company name
while (adGroupIterator.hasNext()) { // Go over all campaings with company id in the name
var adgroup = adGroupIterator.next();
if (adgroup.isEnabled()) { // If campaign is enables, pause it
adgroup.pause();
Logger.log("adgroup " + adgroup.getName() + " was paused.");
}
}
}
// If company_root_id has MORE than 0 jobs
else {
var adGroupIterator = AdWordsApp.adGroups().withCondition('Name CONTAINS "| ' + id + ' |"').get(); // Find all campaigns with the company name
while (adGroupIterator.hasNext()) { // Go over all campaings with company id in the name
var adgroup = adGroupIterator.next();
if (adgroup.isPaused()) { // If campaign is paused, enable it
adgroup.enable();
Logger.log("adgroup " + adgroup.getName() + " was enabled.");
}
}
} // End If Else
}
}
Many thanks for any help!
With the help of Calin in this post: https://www.en.advertisercommunity.com/t5/Advanced-Features/Script-to-pause-Adggroups-based-in-information-from-a-Merchant/m-p/1024590#
I solved my problem.
To read the XML correctly, I used:
// Load an XML file:
var xmlURL = "XML_MERCHANT_URL_HERE";
var xmlFile = UrlFetchApp.fetch(xmlURL);
// Parse the XML file:
var document = XmlService.parse(xmlFile);
var ns = XmlService.getNamespace("http://base.google.com/ns/1.0");
var rss = document.getRootElement().getChildren(); //root element is <rss>; it's children are actually only one, <channel>
var entries = rss[0].getChildren('item'); //getting all 'item' children of the first rss element, <channel>
// Go through all children of <deepdive_pages>:
Logger.log(entries.length);
for (var i = 0; i < entries.length; i++) {
var id = entries[i].getChild('id',ns).getText();
var availability = entries[i].getChild('availability',ns).getText();
//Logger.log("ID: "+id+", Availability: "+availability);
Before I did'nt declared the XML namespace and I was using getchild, but in this case I need to use getChildren.

How can I get the data entered into a Google Form emailed to me?

I made some modifications to a Google Script I found online, but not knowing how to script so well, I'm sure I'm missing something here.
My goal is to have all the information submitted through a Google Form to then be emailed to me or a group I'll create.
This script here does email me the info, but it's all added as a single line without even mentioning the questions.
I'm a total newb, but I'm sure this could be solved with some kind of command or event that I'm unaware of.
Take a look:
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First column of data to process
var numRow = 1; // Number of columns to process
var dataRange = sheet.getRange(startRow, 1, numRow, 10)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var message1 = row[1,2,3,4,5];
var message2 = row[2];
var message3 = row[3];
var message4 = row[4];
var message5 = row[5];
var message6 = row[6];
var message7 = row[7];
var message8 = row[8];// Second column
var emailSent = row[10]
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "New Hire On The Way!";
MailApp.sendEmail("itgroup#mycompany.com",subject,message1+message2+message3+message4+message5+message6);
sheet.getRange(startRow + i, 10).setValue(EMAIL_SENT);
}
}
}
That whole "EMAIL_SENT" was my attempt at having the script not resend info that was already entered.
If there is a better way of doing this, I'd love to hear it.
Thank you so much!
You can set this function as a trigger for onFormSubmit in the response sheet.
Source: Get Google Forms data in an Email Messages
function SendGoogleForm(e) {
var email = Session.getActiveUser().getEmail();
var subject = "Google Docs Form Submitted";
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for ( var keys in columns )
message += columns[keys] + ' :: '+ e.namedValues[columns[keys]] + "\n\n";
MailApp.sendEmail(email, subject, message);
}
if your just wanting the email to have a little more structure you can just add html to the individual messages. Depending how crazy your want to get is up to you. Here is a simple change that you can try it should have a little more structure. Replace this with your if statement
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "New Hire On The Way!";
MailApp.sendEmail("itgroup#mycompany.com",subject,message1+"<br />"+"<br />"+"<br />"+message2+"<br />"+"<br />"+"<br />"+message3+"<br />"+"<br />"+"<br />"+message4+"<br />"+"<br />"+"<br />"+message5+"<br />"+"<br />"+"<br />"+message6+"<br />"+"<br />"+"<br />");
sheet.getRange(startRow + i, 10).setValue(EMAIL_SENT);
}
All I did here is add breaks between your messages. This should create some spaces. You can always go crazy with inline css and html. www.w3schools.com is always a great place to start for beginners. Good Luck and happy coding!

Query String for pre-filling html form field

I manage a website for an organization that has separate chapter sites. There is a membership signup form that is on the main website that each chapter links to. On the form there is a dropdown box that allows a person to choose the chapter they want to join. What I would like to do is have each chapter website use a specific link to the form that will preselect their chapter from the dropdown box.
After searching the web, I found that I will probably need to use a Javascript function to utilize a Query String. With all my searching, I still can't figure out the exact code to use. The page is a basic HTML page...no php and it is hosted on a linux server.
Any help would be greatly appreciated.
If you format your url like this:
www.myorg.com?chapter=1
You could add this script to your html head:
function getparam(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
function loadform()
{
var list = document.getElementById("mychapterdropdown");
var chapter = getparam("chapter");
if (chapter>=0 && chapter < list.options.length)
{
list.selectedIndex = chapter;
}
}
The in your html body tag:
<body onload="loadform();" >
Could probably add more validation checks but that's the general idea.
It sounds like what you are looking for are GET or POST requests. For instance, if your user selects "Chapter A" from your form and hits select, you can allow redirects from another site (for instance http://www.yoursite.com/form.html?chapter=A) to allow Chapter A to be preselected. In Javascript this is done by
var chapter="";
var queryString = location.search.substring(1);
if ( queryString.length > 0 ) {
var getdata = queryString.split("&");
var keyvalues;
for(var i=0; i < getdata.length; i++){
keyvalues = getdata.split("=");
}
} else {
chapter = "Not Found";
}
document.getElementById( "ChapterID").value = keyvalues['chapter'];
This is untested, so don't hold me to it :).
maybe something using parse_url
$params = parse_url()
$query = $params['query'];
$query_pairs = explode('&',$query);
$key_val = array();
foreach($query_pairs as $key => $val){
$key_val[$key] = $val;
}
http://www.php.net/manual/en/function.parse-url.php
You would probably have to use an dynamic ajax content. Use the following javascript to read the querystring, then load the html file in that div using this javascript.

Categories