Quotation mark converted into code in string - json

I have a use case where an object was passed from server to client through EJS like below:
res.render('mytemplate', {data: myobject});
<script type='text/javascript'>
<% if (typeof data !== 'undefined' && data) { %>
data: '<%= JSON.stringify(data) %>',
<% } %>
</script>
I'm having this issue that in the client code, the returned stringified object looks like
{"key":"value"}
whereas it is supposed to be
{"key":"value"}
So when I do JSON.parse() in the client code I get an error. How do I keep the quotation marks in the string instead of the special character code? Thanks!

I think you need to use the unescaped way in your template:
data: '<%- JSON.stringify(data) %>',
Note the <%- instead of <%=
See the documentation "Tags" section: https://ejs.co/#docs

Related

#Html.raw with XML string

I am pulling an XML template from the database and then using this template in my view (DYMO labels).
My issue is that when I use #Html.Raw, even with quotes around it, it only reads the first line as "Text" and after the line break reads the rest of the XML file as code on the page.
Picture below:
1
The first line appears fine, but starting with <DesktopLabel Version the XML is rendered as not plain text inside quotes.
Here is my current behind the scenes code:
var labelXml = '#Html.Raw(Model.XML)';
I need the entirety of the string stored in quotes ("", ''). Any help?
you need to encode the xml
#Html.Raw(Html.Encode(Model.XML))
I was able to resolve this issue using a JSON AJAX controller action call. Code and explanation below in case anyone ever needs help on this:
try {
var _size = "#Model.size";
$.ajax({
data: { size: _size},
type: "POST",
url: "/Unit/GetXMLFile/",
success: function (data) {
var labelD = dymo.label.framework.openLabelXml(data);
labelD.print(printerName);
},
error: function (response) {
alert("error" + response.responseText);
}
});
}
catch(err) {
alert("Couldn't load label");
return;
}
Because we are directly injecting the XML string into our DYMO framework we prevent any chance of encoding the <> characters as &lt and &gt.
I believe that the root issue came from attempting to transfer XML strings from Viewmodel > Javascript. Even attempting to store the XML in the viewmodel and store as plain text once inside the view did not work.
The only method that worked was the AJAX direct controller action that keeps XMLs format without any conversion.
Here is my controller action:
[HttpPost]
public JsonResult GetXMLFile(string size)
{
string XML = "";
if (size == "Small")
{
XML = db.UnitLabels.Where(x => x.Size == "Small").Select(x => x.LabelXML).FirstOrDefault();
}
else
{
XML = db.UnitLabels.Where(x => x.Size == "Large").Select(x => x.LabelXML).FirstOrDefault();
}
return Json(XML, JsonRequestBehavior.AllowGet);
}

cannot able to pass data from express to ejs?

i tried to pass a data from js file(sample.js) to ejs using res.send("filename.ejs",data) by converting a object into JSON where JSON data is displaying on console, but while trying to pass it showing an error
TypeError: Cannot create property '_locals' on string
can some one help with this and tell me how to call them in ejs file
res.send() is used for send data there is no need to point ejs file
res.send takes array as parameter (res.send([body])) and you can get it in ejs like {{ data }}
for example
NODEJS
res.send({message: 'hello'})
filename.ejs
<div>{{ message }}</div> or <%= JSON.stringify(message) %>
also as Express 5x does not support res.send() method you can use
res.status(200).send({message: 'hello})
(you did not admit you express version)
Note that you should not use the .ejs extension in res.render, despite other answers to your question suggesting that you do so.
When you call res.render('myView'), ejs looks for a template called myView.ejs in a folder called views (which is set as the default folder to use by ejs)
for example:
res.render('myView.ejs',{
data:data,
foo:'foo'
});
ejs will look for a view called myView.ejs.ejs (or it might just fail alltogether).
To access the data on your template, you would do the following:
app.js:
app.get('/somePathHere', function(req, res) {
res.render('myView',{
data:data,
foo:'foo'
});
});
myView.ejs:
<% data.forEach(function(item) { %>
//do something
<% }); %>
<%= foo %>
Note that when accessing a variable, you use the <%= varNameHere %>, and when writing any type of function, you would omit the =.
You're sending data to your view so update your code with this and try
res.render("filename",{
data:"hello"
});
Or you can pass whole data
res.render("filename",{data:data});
And in your ejs file access it like this
<div> <%= data %> <div>

Can I render JSON.parse data to EJS?

I am new to NodeJS and Express (to coding, in general). I am trying to render data to an EJS view page so I can manipulate it in the front end. It looks something like this:
app.set('view engine','ejs');
var str = JSON.parse('[{"name":"bill", "age":"26"}, {"name":"jeff", "age":"32"}]');
str.forEach(function(data){
console.log(data.name);
});
app.get('/data', function(req, res){
res.render('data', {str:str});
});
I try to test it in the EJS file by typing in <%= data %> the output I am getting in the browser is [object Object],[object Object]. I feel like I am missing a few piece. Can someone please help me out?
Thanks
Edit:
Thanks Booligoosh. Just want to add that I had to convert it back to JSON in the EJS side afterward to make it work. :)
You are attempting to print an array containing two objects to the ejs template. In a template you only print strings.
To print an object to the template we first need to stringify it:
<%= JSON.stringify(str) %>
To access a property of the object in your array we reference the array index and the property key:
<%= str[0].name %>
To iterate over the array and print out all the values we use a forEach:
<ul>
<% str.forEach(function(o) { %>
<li><%= o.name %> - <%= o.age %></li>
<% }); %>
</ul>
In ejs template we can render json object as below:
<%- JSON.stringify(user) %>
I tried with <%= JSON.stringify(user) %> (<%=) but it will print asci code values for double-quotes.
Try this:
app.set('view engine','ejs');
var str = JSON.parse('[{"name":"bill", "age":"26"}, {"name":"jeff", "age":"32"}]');
str.forEach(function(data){
console.log(data.name);
});
app.get('/data', function(req, res){
res.render('data', {str: JSON.stringify(str) });
});
You will need to convert your JSON object back to a string before passing it to the template using JSON.stringify, otherwise it will just be rendered with .toString, which returns [object Object],[object Object].

Yii ajax return html page

there! I have a problem with receive data from my ajax query. It's return html code of the page.
My ajax code
$.ajax({
url: 'index.php?r=site/page&view=mail',
type: 'post',
data: {action: 'smtp_save', smtp_login: login, smtp_password: password, smtp_server: server, smtp_port: port },
success: function($output) {
//debug message
alert($output);
}
})
Php, just for test only
if(isset($_POST['action']) && !empty($_POST['action']))
{
echo 'test';
}
What do you expect? of course it return HTML. If you do not set the return data type specifically, it tries to guess the dattatype.
And as you output only "test" so it is HTML of course.
If you want JSON you should do 2 things:
set the type to JSON with dataType:'json'
user this php code: echo json_encode('test')
And if you do this all in the controler/action, then you should add Yii::app()->end();
after the echo, otherwise Yii renders the whole page output. This way you only get what you have echod out

How to send JSON to Flash from Node.js

I want a simple example of how to send data from a nodeJS server as JSON to Flash, then Flash decodes the JSON. This is part of what I want:
Server
json = {name : "Person", id: "1"}
Flash
myinput.text = json.id + ":" + json.name
Use AMF.js, which is the subject of a related question which discusses the syntax and debugging process.
On server-side:
app.post('/login', (req, res) => {
//Some code with error here...
errorModel = {
code: 400,
message: 'Wrong username or password'
}
req.flash('error', JSON.stringify(errorModel))
res.redirect('/login')
})
On client-side (for example using EJS view):
<% if (messages.error) { %>
<p>
<%= JSON.parse(messages.error).message %>
</p>
<% } %>