Importing a variable into HTML - javascript

So I am currently trying to take a variable from my Main.js and import into a file called Iframe.html, the subject is a string containing the subject of a ticket from zen-desk I have the api working and it is grabbing the ticket subject however when I then try to implement that into the recognition system for the "BC-", it doesn't recognise.
This is the Main.js file with the variable "Subject" defined
function showInfo(data) {
var requester_data = {
//'email': data.ticket.address
//'name': data.ticket.name
'description': data.ticket.description,
'subject': data.ticket.subject
};
var source = $("#requester-template").html();
var template = Handlebars.compile(source);
var html = template(requester_data);
$("#content").html(html);
}
And this is the Iframe.html file that I am trying to import the variable "Subject" across to:
<!--BC-Check six digit-->
<script type="text/javascript">
function bc_check() {
var str = {{subject}};
var res = str.substring(str.indexOf("BC-"), str.indexOf("BC-") + 9);
document.getElementById("recognize").innerHTML = res;
}
</script>

Try to extract the variable requester_data out of the function but give it values inside it like you're doing it already.
I think your problem is that the variable requester_data belongs to the function and doesnt to the scope.

Related

Issue with accessing jinja python list in javascript

I have a python list called "devices" that looks something like this:
[{
'Version': 'V14E',
'DeviceID': 'e00fce68281671574f416a8c',
'TerminationDate': '2050-12-31',
'Latitude': 31.322139613573903,
'ActivationDate': '2021-01-04',
'Longitude': -101.93960164357534,
'DeviceName': 'Hans_Gruber-1'
}, {
'Version': 'V14E',
'DeviceID': 'e00fce68e1265e12e12fa02a',
'TerminationDate': '2050-12-31',
'Latitude': 31.32151602493975,
'ActivationDate': '2021-01-04',
'Longitude': -101.93948944894449,
'DeviceName': 'Hans_Gruber-2'
}]
In my flask app, I pass this list to my html file by the name "devices_test" using json.dumps() to correctly format the data to be used in java script.
return render_template("json_form.html",
devices = devices, components = components, operator = operator, name = site_name,
devices_test = json.dumps(devices))
Here is me trying to test out an answer I have seen on another post here via the "data" variable:
function update_device_form(strDevice) {
var data = {
{
devices_test | safe
}
};
var device_index = document.getElementById("devices").selectedIndex;
if (device_index == 0) { //IOW if no device is selected
document.getElementById("device_id").value = "";
} else {
document.getElementById("device_id").value = '';
}
But I get errors such as "Declaration or statement expected" and "Property assignment expected" and "',' expected". What am I doing wrong here?
You can use string to remove the error var data = "{{devices_test|safe}}"
Now data is not javascript object, it is a string, you need to use JSON.parse and also replaceAll.
var data = "{{devices_test|safe}}"
var data = data.replaceAll("'",'"') // replace single quote to double
var data = JSON.parse(data)
one line
var data = JSON.parse("{{devices_test|safe}}".replaceAll("'",'"'))

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

Html templates loaded asynch (JQuery/JavaScript asynch)

So I'm making a webpage with some code snippets loaded in from txt files. The information to paths and locations of the txt files are stored in a json file. First I'm loaing the json file looking like this
[
{"root":"name of package", "html":"htmlfile.txt", "c":"c#file.txt", "bridge":"bridgefile"},
{"root":"name of package", "html":"htmlfile.txt", "c":"c#file.txt", "bridge":"bridgefile"}
]
After loaded I'm using templates from my index.html file and then inserting the templates. My problem is that its happening asynch so that the page never looks the same because of the asynch nature of js.
Here is what my jquery code for loading and inserting looks like:
$(document).ready(function () {
var fullJson;
$.when(
$.get('/data/testHtml/data.json', function (json) {
fullJson=json;
})
).then(function(){
for(var i=0; i<fullJson.length; i++){
templefy(fullJson[i],i);
}
})
var templefy = function (data, number) {
//Fetches template from doc.
var tmpl = document.getElementById('schemeTemplate').content.cloneNode(true);
//Destination for template inserts
var place = document.getElementsByName('examples');
//Set name
tmpl.querySelector('.name').innerText = data.root;
//Next section makes sure that each tap pane has a unique name so that the system does not override eventlisteners
var htmlNav = tmpl.getElementById("html");
htmlNav.id += number;
var htmlLink = tmpl.getElementById('htmlToggle');
htmlLink.href += number;
var cNav = tmpl.getElementById('c');
cNav.id += number;
var cLink = tmpl.getElementById('cToggle');
cLink.href += number;
var bridgeNav = tmpl.getElementById('bridge');
bridgeNav.id += number;
var bridgeLink = tmpl.getElementById('bridgeToggle');
bridgeLink.href += number;
//Auto creates the sidebar with links using a link template from doc.
var elementLink = tmpl.getElementById('elementLink');
elementLink.name +=data.root;
var linkTemplate = document.getElementById('linkTemplate').content.cloneNode(true);
var linkPlacement = document.getElementById('linkListWVisuals');
var link = linkTemplate.getElementById('link');
link.href = "#"+data.root;
link.innerText = data.root;
linkPlacement.appendChild(linkTemplate);
//Fetches html, c# and bridge code. Then inserts it into template and finally inserts it to doc
$.get("/data/" + data.root + '/' + data.html, function (html) {
tmpl.querySelector('.preview').innerHTML = html;
tmpl.querySelector('.html-prev').innerHTML = html;
$.get('/data/' + data.root + '/' + data.c, function (c) {
tmpl.querySelector('.c-prev').innerHTML = c;
$.get('/data/' + data.root + '/' + data.bridge, function (bridge) {
console.log(bridge);
tmpl.querySelector('.bridge-prev').innerHTML = bridge;
place[0].appendChild(tmpl);
})
})
})
}
});
So yeah my problem is that it just fires in templates whenever they are ready and not in the order written in the json file.
I'll take whatever help I can get..Thank you :)
To my knowledge, there is no golden method and i usually apply one of the following options:
1) Preload the files separately e.g. create key "body" for each entry in your json and then set the value of it to the contents of the file.
2) Do not display items until they are not fully loaded in the DOM and before you show them, sort them in the DOM by e.g. their position in the json array.
Hope it helps.
My only way out has been to make the whole application in angular instead and using a filter to make sure that I get the right result.

Javascript / Jquery - How to set a variable name based on a variable

This has been asked a bunch of times before but I'm not grasping it.
In the following..
var variableName = "hello";
How do I make the variable name 'variableName' based on another variable?
PHP Example
$a = 'hello';
$$a = 'hi'; // same as $hello..
echo $hello; // and $hello outputs 'hi'
I specifically need this variable variable to be used for localstorage so it may be syntax that I'm having a problem with.
What I'm Using It For (you can probbaly skip to This Seems To Work)
I want to generate a unique variable name for storing information in local storage. Variable name will be based on the post id of the wordpress post/page which I retrieve with php.
For example we will say the post id is 3333
I add the letters id to the beginning of each post id
So now I have id3333
var postIdNumber = 'id3333';
Then I get 3 other pieces of information that I want to store into local storage about this post (for simplicity I have shown an example output, not the code to get it)
var postURL = 'website.comm/a-wp-post/';
var postTitle = 'A Wordpress Post';
var postThumb = 'website.comm/images/thumb3333.jpg';
Now I want to store this information into local storage
var lsTest = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('lsTest', JSON.stringify(lsTest));
That works fine. Except that I want to be able to store multiple posts into local storage to retrieve later from a 'my favourite posts' page.
So I need a dynamic variable name.
For post ID 3333 I need the variable currently named lsTest to be named id3333
For post ID 4444 I need the variable currently named lsTest to be named id4444
This seems to work (Though I dont fully comprehend it)
solution modified from https://stackoverflow.com/a/5187652/3377049
var variableVariable = {}
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
jQuery('.test-div').text(variableVariable[vv]); // outputs id3333
While this does not..
var variableVariable = {} // also, should this have a ';' ?
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
var variableVariable[vv] = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('variableVariable[vv]', JSON.stringify(variableVariable[vv]));
In PHP I could maybe do something like this.. (for examples sake i'm mixing php variables into JS)
$uv = 'id3333';
$$uv = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('$$uv', JSON.stringify($$uv));
You just need to create an object of objects, keyed off of the unique post id. But then you need to stringify the object before storing it, and parse it when retrieving it.
function saveObject(key, object) {
object = JSON.stringify(object);
window.localStorage.setItem(key, object);
}
function getSavedObject(key) {
var saved = window.localStorage.getItem(key);
if (saved) {
return JSON.parse(saved);
} else {
return null;
}
}
your object:
var lsTest = {
id3333: {
postUrl: postUrl1,
postTitle: postTitle1,
postThumb: postThumb1,
},
id4444: {
postUrl: postUrl2,
postTitle: postTitle2,
postThumb: postThumb2,
}
}
store it:
saveObject('myUniqueSiteName', lsTest);
retrieve it:
var lsTest = getSavedObject('myUniqueSiteName');
adding a new post:
var lsTest = getSavedObject('myUniqueSiteName');
var postId = 'id555';
lsTest[postId] = {
postUrl: postUrl3,
postTitle: postTitle3,
postThumb: postThumb3,
}
saveObject('myUniqueSiteName', lsTest);
Variable variables are not a good idea even in PHP. Just make an array or a hash (which is an object, but it's used as a hash or map, where you can add and delete properties or entries as you please).
var posts = {};
var someId = 3333; //or '3333' if it isn't a number
posts[someId] = {
URL: postURL,
title: postTitle,
thumb: postThumb
};
localStorage.setItem('post' + someId, JSON.stringify(posts[someId]));
A property named "foo" on an object named "bar" can be accessed like so:
bar.foo = 'baz';
console.log(bar.foo);
or like so:
bar['foo'] = 'baz';
console.log(bar['foo']);
Which is the same as:
var name = 'foo';
bar[name] = 'baz';
console.log(bar[name]);
Finally, the global object in JavaScript (which in the browser is window) "holds" the global variables.
var myGlobal = 10;
console.log(window.myGlobal); // logs 10
var globalName = 'foo';
window[globalName] = 'baz';
console.log(foo); //logs 'baz'
Using global variables in general is discouraged. Using them to store posts where the name of the var is the id is highly unorthodox and many JS developers would consider it simply wrong.

How to return json formated array data from jquery to html

Example of fetching data from FB...
$(document).ready(function(){
var name;
var link;
var gender;
var id;
$.getJSON( "http://graph.facebook.com/4/", function( json ) {
name = json.name;
link = json.link;
gender = json.gender;
id = json.id;
var person = {name:name,link:link,gender:gender,id:id};
console.log(person);
// This gives me exactly what I need but only in console view.
$('html').text(person);
// This just writes [object Object] inside my window
return person;
});
});
I appreciate your help, I know this are the basics but right now my brain doesn't work as it should :\
I, too, would recommend some sort of templating system like underscores, handlebars, mustasche etc. However, if it's limited use you could do it yourself, instead of using an entire framework for one template.
You need some placeholders in your HTML. In the example, i use Mustasche.js-style placeholders. Example:
<html>
<body>
<ul>
<li>name: {{name}}</li>
<li>gender: {gender}</li>
<li>link: {{link}}</li>
<li>id: {{id}}</li>
</ul>
</body>
</html>
Then we want to replace the placeholder with the appropriate value, which could be done like this:
...
$.getJSON( "http://graph.facebook.com/4/", function( json ) {
name = json.name;
link = json.link;
gender = json.gender;
id = json.id;
var person = {name:name,link:link,gender:gender,id:id};
// Get the current HTML from the selector
var template = $("html").html();
// Replace each placeholder w/ the correct thing
template = template.replace("{{name}}", name);
template = template.replace("{{link}}", link);
template = template.replace("{{gender}}", gender);
template = template.replace("{{id}}", id);
// Write the new HTML to the selector
$("html").html(template);
return person;
});
...
I recommend using a template function like _.template()
var compiled = _.template("<p>Name: <%= name %></p>");
compiled(person);
//<p>Name: Theresa</p>
http://underscorejs.org/#template

Categories

Resources