I have this response data from the server that I authenticate.
<session session-guid="D39C1215-2F31-8641-E5T2-C7G35RT69127" user-id="34"> </session>
How can I get the value of session-guid and user-id and store them into 1 variable for each.
Thank you.
In plain Javascript in a modern browser you can use document.querySelectorAll().
For example, assuming you only have one session tag:
var session = document.querySelectorAll("session")[0];
var session_guid = session.getAttribute("session-guid");
var user_id = session.getAttribute("user-id");
console.log("session-guid: " + session_guid);
console.log("user-id: " + user_id);
If you have more that one session tag you can use forEach on the results of querySelectorAll() to locate the one you want. If you know that you're only going to have one session element you can use document.querySelector() instead of document.querySelectorAll()[0].
Here is one way to get the values client side. For this method you will need to add any custom class to your element like below:
Now write below lines of code inside tag:
var $mySession = jQuery(document.getElementsByClassName("mySession"));
for (i = 0; i < $mySession.length; i++) {
var sessionguid = jQuery($mySession[i]).attr('session-guid');
var userid = jQuery($mySession[i]).attr('user-id');
console.log(sessionguid);
console.log(userid);
}
You can check the values of "sessionguid" and "userid" variable in your browser console.
Here is what you can do to get the required data from the XML.
function getXMLData(xml) {
var txt, xmlDoc;
//get the responseXML
xmlDoc = xml.responseXML;
txt = "";
//get all the session nodes
var sessions = xmlDoc.getElementsByTagName("session");//this returns a array of nodes
for(var i =0;i<sessions.length;i++){
//iterate over nodes and get the attributes
txt += sessions[i].getAttribute("session-guid")+"<br />";
}
document.getElementById("demo").innerHTML = txt;
}
this function accepts the response as a parameter. And then extracts out the sessions nodes and the required attribute. You can modify it according to your requirements.
Here is a PLNKR demo for the same
Related
I'm creating a document merge (mail merge) from Google App Maker to a Google Document template. I can do so successfully when merging one single record, but how do you merge several records into the one document?
I have an purchase_orders parent record which has several purchase_order_line_items child records but I can't seem to get all of these records into a single document merge.
A similar question (Document Merge with Google App Maker) was asked by by Johan W with a comprehensive answer by Markus Malessa and Pavel Shkleinik (thank you!). However, it only caters for cases when you are merging one single record.
I have tried to build on their answer by using a second for loop to get the data of all associated child records. The script runs but only seems to merge the first child record; not all of them.
Here is an example of the server-side code I've tried to use:
function Export(key, key2) {
// Get the parent record by its key, which was passed by the first parameter above
var record = app.models.Purchase_Orders.getRecord(key);
// Get the first child record by its key, which was passed by the second parameter above
var childRecord = app.models.Purchase_Order_Line_Items.getRecord(key2);
// Get the Google Document which will be used as a template for this merge
var templateId = '1Xbt8camqHJYrhBnx0a6G2-RvTvybqU0PclHifcdiLLA';
//Set the filename of the new merge document to be created
var filename = 'Document for Customer ' + new Date();
//Make a copy of the template to use as the merge document
var copyFile = DriveApp.getFileById(templateId).makeCopy(filename);
//Get the Google Docs ID of the newly created merge document
var copyDoc = DocumentApp.openById(copyFile.getId());
var copyBody = copyDoc.getBody();
// Replace the field names in the template with the field data from the parent record
var fields = app.metadata.models.Purchase_Orders.fields;
for (var i in fields) {
console.log(i);
var text = '<<' + fields[i].name + '>>';
var data = record[fields[i].name];
if (data !== null) {
copyBody.replaceText(text, data);
} else {
// do nothing
}
}
// Replace the field names in the template with the field data from the child records
childFields = app.metadata.models.Purchase_Order_Line_Items.fields;
for (i in childFields) {
console.log(i);
var childtext = '<<' + childFields[i].name + '>>';
var childdata = childRecord[childFields[i].name];
if (childdata !== null) {
copyBody.replaceText(childtext, childdata);
} else {
// do nothing
}
}
}
How can I improve my code so that all associated child records are merged into a single document?
How can I set up my Google Document template to cater for any number of child records?
Rather than passing in the child record key via a second parameter, I would suggest just passing in the parent key and then changing your function as follows:
function Export(key) {
// Get the parent record by its key, which was passed by the first parameter above
var record = app.models.Purchase_Orders.getRecord(key);
// Get the first child record by its key, which was passed by the second parameter above
var childRecords = record.Purchase_Order_Line_Items;
// Get the Google Document which will be used as a template for this merge
var templateId = '1Xbt8camqHJYrhBnx0a6G2-RvTvybqU0PclHifcdiLLA';
//Set the filename of the new merge document to be created
var filename = 'Document for Customer ' + new Date();
//Make a copy of the template to use as the merge document
var copyFile = DriveApp.getFileById(templateId).makeCopy(filename);
//Get the Google Docs ID of the newly created merge document
var copyDoc = DocumentApp.openById(copyFile.getId());
var copyBody = copyDoc.getBody();
// Replace the field names in the template with the field data from the parent record
var fields = app.metadata.models.Purchase_Orders.fields;
for (var i in fields) {
console.log(i);
var text = '<<' + fields[i].name + '>>';
var data = record[fields[i].name];
if (data !== null) {
copyBody.replaceText(text, data);
} else {
// do nothing
}
}
// Replace the field names in the template with the field data from the child records
var childFields = app.metadata.models.Purchase_Order_Line_Items.fields;
var table = [];
var tableheader = [];
for (i in childFields) {
console.log(i);
tableheader.push(childFields[i].displayName);
}
table.push(tableheader);
for (i in childRecords) {
var data = [];
for (var j in childFields) {
data.push(childRecords[i][childFields[j].name]);
}
table.push(data);
}
copyBody.appendTable(table);
The table building is based on a 2D array and the documentation is here https://developers.google.com/apps-script/reference/document/table. But you will also need to remove your prebuilt table in favor of just appending a table instead. This way you are not dependent on the quantity of child records being fixed like they currently are in your document template. Also, the variable for childRecords may or may not work, I have not tested this since I am unsure if prefetch works in conjunction with .getRecord(key). This may require some additional testing but hopefully this will provide enough guidance.
Thought I would add this as an alternative. Lets say you keep your table but remove all the rows with exception for the header row then you could still use DocumentApp service to add your rows to the table like so:
var tableheaderfieldnames = ['Quantity_for_PO', 'Inventory_Item.id', 'Unit_Price']; //set a fixed table header with the field names, uncertain if the table header for the related inventory item will work or not
var table = copyBody.getTables()[0];
for (i in childRecords) {
var row = table.appendRow();
for (var j in tableheaderfieldnames) {
row.appendTableCell(childRecords[i][tableheaderfieldnames[j]]);
}
}
Keep in mind that AM does not allow you to use FK references, so for your inventory item that appears to use a fk field you may need to tinker around with setting the proper name reference for when you are trying to fill in the item in your table.
The javascript snippet that we have is :
Link
I would like to retrieve the value of data-test-socialmedia type. Based on that I would like to add the conditional statement to check if the data-test-socialmedia type is facebook. As we have many data attributes like this in the site.
I tried several ways and I get object as the value. But i need the actual value in this case it is facebook. Kindly help.
//first get element
var el = document.getElementsByClassName('n-contact')[0];
//get data and replace single quotes with double quotes to create valid JSON
var d = el.dataset.testSocialmedia.replace(/'/g, '"')
//parse JSON to javascript object
var parsed = JSON.parse(d, null)
//get country if type is facebook
if(parsed.options == 'facebook')
console.log(parsed.options.country)
Link
var str = document.querySelector('.n-contact').getAttribute('data-test-socialmedia').replace(/'/g,'"');
var obj = JSON.parse(str);
var result = obj.type;
console.log(result);
it would work.
With jQuery
var elementData = $(".n-contact").attr("data-test-socialmedia").replace(/'/g,'"'),
parsed = JSON.parse(elementData);
console.log(parsed);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Link
I am learning extendscript for scripting adobe illustrator.It is very difficult for me to write xml related parsing.
My problem statement is given below:- "I have taken three text boxes namely name,city and country."name" is a unique key.when i click ok button the data must be saved in xml if name does not exist else update the previous name with out creating duplicate.All the names in xml file are displayed in list box.The date of particular name could be deleted by remove button.which will remove data in selected item of list box.
The code i tried to do is:-
var myWindow = new Window ("dialog", "Form");
var txt1 = myWindow.add ("edittext");//name unique
var txt2 = myWindow.add ("edittext");//city
var txt3 = myWindow.add ("edittext");//country
var btn=myWindow.add ("button", undefined, "OK");
btn.onClick = function () {
for (i=0;i<numberofnamesinxml;i++)//coding required
{
if(txt1.text!=xmlname[i]) // to verify name not there since it is like primary key
xmlFile.open("a");
xmlFile.write(root.toXMLString());
xmlFile.copy ('C:/data.xml');
xmlFile.close();
//myList refresh
}
}
var myList = myWindow.add ("listbox");
for (i=0;i<numberofnamesinxml;i++)//coding required
{
config='C:/data.xml';
config.open("r");
data= xmlname[i] //here i need to set data to
config.close();
myList.add ("item", data);
}
var btn1=myWindow.add ("button", undefined, "remove");
btn1.onClick = function () {
myList.remove (myList1.selection[i]);
//xml data having this list name must be removed
}
myWindow.show ();
Please kindly help me.
This should not be considered a full answer. I still post it because it might help finding one.
This is what I tried to write as an answer. The read/write part works but the checking of an element exists fails.
if the child is not an exact match, xml.contains(xml) will not return true.
var path = '~/Desktop/test.xml';
var xmlfile = File(path);
if (!xmlfile.exists) {
$.writeln('xml file does not exist. Creating new one');
xmlfile = new File(path);
xmlfile.open('w');
xmlfile.write('<Root></Root>');
xmlfile.close();
}
xmlfile.open('r');
xmlcontent = xmlfile.read();
xmlfile.close();
//$.writeln(xmlcontent);
var xml = new XML(xmlcontent);
// here the problems start
// the check is only working for known elements
var child = new XML('<name data="bob"></name>');
if (xml.contains(child)) {
child.#data = 'jim';
$.writeln('A child called "name" exists. Update');
xml.replace('name', child);
} else {
$.writeln('no child called "name" exists. Append');
child.#data = 'bob';
xml.appendChild(child);
}
xmlfile.open('w');
xmlfile.write(xml.toXMLString());
xmlfile.close();
My real answer is:
Use JSON instead.
I'm trying to build a search option where user will input their ID and they will see the result of that corresponding ID which is stored in google spreadsheet.
Like user will input:
1 and they will see result : Nitu
5 and they will see result : Dipon
<input id="id" type="text" placeholder="Your ID">
<input id="search" type="submit" value="Search">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function displayContent(json) {
var string = "<table>";
var len = json.feed.entry.length;
for (var i=0; i<len; i++) {
var id = json.feed.entry[i].gsx$id.$t;
var name = json.feed.entry[i].gsx$name.$t;
string += '<tr><td>' + id + '</td><td>' + name + '</td></tr>';
}
string += "</table>";
$(string).appendTo('body');
}
</script>
<script src="http://spreadsheets.google.com/feeds/list/1WMvFqepPmQUVwTFFUZW_3SfSt1ZBr_AEy_XdUXZ72ng/od6/public/values?alt=json-in-script&callback=displayContent" type="text/javascript"></script>
I can fetch data from my google sheet using the above code snippet. But I don't want to fetch all data at a time. I want only specific data based on search with ID.
So now how can I integrate this search feature in javascript?
You can use Structured Query for google spreadsheet API.
So if make a GET request with proper Structured Query and you will get the relevant data only. in your case add sq=id==5 as query parameter.
So rather then get the whole data onload and parse it afterwads, you should make a function which will make proper GET request and fetch you Only the data you need.
var fetchName = function(ID, workSheetID){
var url = 'https://spreadsheets.google.com/feeds/list/'+workSheetID+'/od6/public/values?sq=id='+ID+'&alt=json-in-script&callback=?';
$.get( url, function( data ) {
//Parse and Do Your Stuff Here
});
}
Plunker Sample
Hope this helps. Cheers !!
instead of doing a for loop just use filter to filter the corresponding ID. For exmaple:
function displayContent(json) {
var output = json.feed.entry.filter(function(name){
return name.gsx$id.$t === '2'
})
$('body').append(" <p>" + output[0].gsx$name.$t + "</p>");
Heres the edited version, just replace '2' with your id or with the input value getter and it should work. Notice you need to reference the output in array like syntax. fiddle
Cross reference your code with the answer provided carefully!
1) your filter: --> return element.gsx$id.$t === 2
The comparison may not return the expected result
--> return name.gsx$id.$t === '2'
2) The returned data if your comparison produces any result would be in the variable 'name'. var name is in an array. You are to use indexes to access the array elements. Therefore, taking that into account, you should change yout code to:
var test = name[0].gsx$id.$t;
Here you are correctly accessing the data returned.
3) Always make sure there is data to access. Your array must not be empty if you try to access it.
I was wondering how to add a html link to each JSON item as it is returned.
php file
//relevant code, $result contains sql query with records from a search
$records = array();
while($array = mysqli_fetch_array($result))
{
$records[] = $array;
}
echo(json_encode($records));
Output html via ajax
function responseReceived(e){
document.getElementById('response').innerHTML = e.target.responseText;
}
Response is a div tag. So I was wondering how would I add html link (to another page) to each item within the json. Because at the moment it outputs json but it's not allowing me to add html.
This is the current output, which is as expected due to me entering data via a form, I just want to add a small html link next to him.
[{"0":"1115","ID":"1115","1":"john","name":"john","2":"male","type":"male","3":"berk","country":"berk","4":"aus","region":"aus","5":"32.43","lon":"32.43","6":"32.54","lat":"32.54","7":"nothing to say","description":"nothing to say"}]
Thanks, in advance.
Where will you get the link from?
Is the returned data the link or is the returned data some text that should be formatted as a link?
If it's the second one, you need to get the link from somewhere.
What you could do is storing some sort of link/id in the database and print that out in the json so it will output something like:
[{"url": "http://example.com", "content": "This is a link!"}]
I presume that you know how to do a ajax call, so let's just continue to the formatting:
// Let's make a function
function createLinks(json){
// Let's parse the JSON first (if it's a string)
json = JSON.parse(json);
// Loop through all the elements
for(var i = 0; i < json.length; i++){
// Check if the fields exist
if(json[i].url && json[i].content){
// Creating a tag
var a = document.createElement("a");
// Let's add the values to the a tag
a.href = json[i].url;
a.textContent = json[i].content;
// ^ or innerHTML if you want to have HTML code there
// Appending to body element (just for this example)
document.body.appendChild(a);
}
}
}
I hope it helps!
This simple code adds a link to every single array item. If you want to transform it to HTML, just create the HTML string and then you can insert it with innerHTML.
var obj = JSON.parse('[{"0":"1115","ID":"1115","1":"john","name":"john","2":"male","type":"male","3":"berk","country":"berk","4":"aus","region":"aus","5":"32.43","lon":"32.43","6":"32.54","lat":"32.54","7":"nothing to say","description":"nothing to say"},{"0":"1115","ID":"1115","1":"john","name":"john","2":"male","type":"male","3":"berk","country":"berk","4":"aus","region":"aus","5":"32.43","lon":"32.43","6":"32.54","lat":"32.54","7":"nothing to say","description":"ggg"}]');
for (var i = 0; i < obj.length; i++) {
obj[i].link = 'Google';
}