Accessing variable value - javascript

I am accessing a html file using readFileSync like this
var content = fs.readFileSync("client/index.html", "utf-8");
and passing content to html.
Students.afterRemote('create', function(ctx, result, next) {
loopback.Email.send({
to: result.email,
from: "person1#something.com",
subject: "Thanks for choosing Us",
text: "text message",
html: content,
var: {
myVar1: 'a custom value'
},
headers: {
"X-My-Header": "My Custom header"
}
})
.then(function(response) {
})
.catch(function(err) {
});
}
In my html file I have this code
result.name + "<p> Your account is created successfully.Thanks for creating an account</p>"
In email it is not giving me result.name's value. It is displaying result.name. How can I access its value? Thanks

When you have something that looks like JavaScript code inside a string, then it is still just part of that string. It will not be executed as if it was JavaScript code.
var result = { name: "bar" };
var string = ` result.name + "<p> Your account is created successfully.Thanks for creating an account</p>"`;
console.log(string);
If you want to use variables, then you'll need to write them in JavaScript and not in a text file you read into a variable.
var result = { name: "bar" };
var string = `<p> Your account is created successfully.Thanks for creating an account</p>`;
var output = result.name + string;
console.log(output);
You could put placeholders in the file and then use a replace call…
var result = { name: "bar" };
var string = `<<<name>>><p> Your account is created successfully.Thanks for creating an account</p>`;
string = string.replace("<<<name>>>", result.name);
console.log(string);
… but at that stage you are creating your own template language and should probably be picking an off the shelf option like Nunjucks
var result = { name: "bar" };
var template = `{{ name }}<p> Your account is created successfully.Thanks for creating an account</p>`;
console.log(nunjucks.renderString(template, result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/nunjucks/3.0.1/nunjucks.min.js"></script>

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("'",'"'))

Importing a variable into HTML

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.

How can I pass a variable to a URL?

I'm trying to send an email with a link in the body that contains a value retrieved from Firebase. I am successfully retrieving the value but I do not know how to append it to the link that is already listed.
Here is the code:
sendinvite() {
var user = firebase.auth().currentUser;
var uid = user.uid;
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
var hashKey = (snapshot.val());
console.log(hashKey)
});
var bcc = [];
for(var e in this.emailinputs){
if (this.emailinputs[e].email==null || this.emailinputs[e].email=="" || !this.emailinputs[e].email.includes("#") || !this.emailinputs[e].email.includes("."))
{
let alert = this.alerCtrl.create({
title: 'Error!',
message: 'There was an error with an email address you entered.',
buttons: ['Ok']
});
alert.present()
}else {
bcc.push(this.emailinputs[e].email);
}
}
if(bcc.length > 0) {
let email = {
bcc: bcc,
subject: 'Nudget Invite',
body: 'Join my grocery list!',
isHtml: true
};
this.emailComposer.open(email);
}
}
I want the variable hashKey to be appended to the URL listed in the body but I'm not sure how to achieve this.
Edit 1
Updated the body to append the variable to the string. I'm not sure where I can place the hashkey from Firebase for it to be referenced properly.
The main problem I see is that you are scoping the 'hashkey' variable to just the firebase...function(snapshot) block. This should be defined at the top near the 'uid' variable, so that all of this code can reference it.
Then in you snapshot function, remove the 'var' in front of hashkey, so it just sets the existing variable.
Also, be sure to check if 'hashkey' has a non-blank value before sending the email.
HTH,
Jim
I think the problem is here:
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
var hashKey = (snapshot.val());
console.log(hashKey)
});
You are creating the var named hashKey within an anonymous function then trying to access hashKey outside of that function.
Try the following instead:
var user = firebase.auth().currentUser;
var uid = user.uid;
var hashKey = null;
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
hashKey = (snapshot.val());
console.log(hashKey)
});
... snip ...
body: 'Join my grocery list!',
... snip ...

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.

string.replace not working in node.js express server

I need to read a file and replace some texts in that file with dynamic content.when i tried string.replace it is not working for the data that i read from the file.But for the string it is working.I am using node.js and express.
fs.readFile('test.html', function read(err, data) {
if (err) {
console.log(err);
}
else {
var msg = data.toString();
msg.replace("%name%", "myname");
msg.replace(/%email%/gi, 'example#gmail.com');
temp = "Hello %NAME%, would you like some %DRINK%?";
temp = temp.replace(/%NAME%/gi,"Myname");
temp = temp.replace("%DRINK%","tea");
console.log("temp: "+temp);
console.log("msg: "+msg);
}
});
Output:
temp: Hello Myname, would you like some tea?
msg: Hello %NAME%, would you like some %DRINK%?
msg = msg.replace(/%name%/gi, "myname");
You're passing a string instead of a regex to the first replace, and it doesn't match because the case is different. Even if it did match, you're not reassigning this modified value to msg. This is strange, because you're doing everything correctly for tmp.
You need to assign variable for .replace() which returns the string. In your case, you need to do like, msg = msg.replace("%name%", "myname");
Code:
fs.readFile('test.html', function read(err, data) {
if (err) {
console.log(err);
}
else {
var msg = data.toString();
msg = msg.replace("%name%", "myname");
msg = msg.replace(/%email%/gi, 'example#gmail.com');
temp = "Hello %NAME%, would you like some %DRINK%?";
temp = temp.replace(/%NAME%/gi,"Myname");
temp = temp.replace("%DRINK%","tea");
console.log("temp: "+temp);
console.log("msg: "+msg);
}
});
replace() returns a new string with the replaced substrings, so you must assign that to a variable in order to access it. It does not mutate the original string.
You would want to write the transformed string back to your file.

Categories

Resources