I want to pass an entire object right into javascript, but it doesn't seem to work.
I tried the {{{data}}} approach and the {{data}} approach like recommended in another post.
I'm doing something like this in the handlebars file:
<script>
var myData = {{data}}; // or even {{{data}}}
</script>
Both of these give me the exception: Uncaught SyntaxError: Unexpected Identifier.
However if I do a
var myDataUrl = "{{data.url}}";
It works fine, but for the first case it prints out "[Object Object"]. Any thoughts on how I can make case 1 work?
To insert Javascript data directly into template, you need to make it into a legal javascript string and pass that string into the template. It needs to be legal Javscript before it gets to the template. Using something like JSON.stringify() is one such way to make legal Javascript, but it isn't the only way.
Here's a piece from a handlebars template of mine that inserts some javascript data structures into the HTML file:
<script>
// temperature data - array of arrays of the form [dateTime, atticTemp, outsideTemp]
var temperatureData = {{{temperatures}}};
// onOffData is an array of [dateTime, str] - where str is "on" or "off"
var onOffData = {{{onOffData}}};
</script>
And, the data passed to the template looks like this (the two method calls return JSON strings):
app.get('/chart', function(req, res) {
var tempData = {
temperatures: data.getTemperatureDataSmallJSON(),
onOffData: data.getFanOnOffDataSmallJSON(),
units: req.cookies.temperatureUnits
};
res.render('chart', tempData);
});
This results in a piece of an HTML file that looks like this:
<script>
// temperature data - array of arrays of the form [dateTime, atticTemp, outsideTemp]
var temperatureData = [[1412752013861,22.19,16.35],[1412753505591,22,16.15],[1412754286561,21.85,15.94]];
// onOffData is an array of [dateTime, str] - where str is "on" or "off"
var onOffData = [[1411786960889,"off"],[1411790853867,"off"]];
</script>
Note, I'm turning the data into JSON and passing that JSON string into the template.
Related
i have an issue with my logged Json String as it replaces the double quotes with "
Controller Code :
var message = new SuccessMessagesVM()
{
Title = successMessageType == (int)EnumHelper.SuccessMessageTypes.Add ? "It's beautiful" : CustomModel.Resources.SuccessMessagesResources.EditFormSuccess,
Message = successMessageType == (int)EnumHelper.SuccessMessageTypes.Add ? CustomModel.Resources.SuccessMessagesResources.AddFormSuccess : CustomModel.Resources.SuccessMessagesResources.EditFormSuccess,
ColorCode = (int)EnumHelper.MessagesCodes.Success
};
var json = JsonConvert.SerializeObject(message);
ViewBag.SuccessMessage = successMessageType == 0 ? null : json;
Javascript just logs the ViewBag.SuccessMessage as following:
console.log('#ViewBag.SuccessMessage');
and the object is displayed as {"Message":"تم إضافة النموذج بنجاح","Title":"It's beautiful","ColorCode":3}
replacing all single quotes with ' and all double quotes with "
I expect the output to be {"Message":"تم إضافة النموذج بنجاح","Title":"It's beautiful","ColorCode":3}
This is because you are using ViewBag variable.
In order to use ViewBag, you can write it as followed:
First, in view:
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var successMessageJson = jss.Serialize(ViewBag.SuccessMessage);
}
Then use it:
<script>
//use Json.parse to convert string to Json
var successMessageInfo = JSON.parse('#Html.Raw(successMessageJson)');
</script>
There's a few different issues and a few different approaches, and the OP doesn't give us any view code, so it's a bit of guesswork.
My feeling is that you should just return the SuccessMessagesVM from your method, and access the properties individually in your view (probably using #Html.DisplayFor and HTML). This will ensure that any redundant quotation marks are never created in the first place, and will give you total control over how the values are displayed.
You should not expect console.log(#ViewBag.Anything) to display properly. If you need the data as a JavaScript object, don't stick it in the ViewBag, as it will get rendered as HTML.
If you must write to a JavaScript object you can, but it begs the question why are you not using an ajax request if all you want is data?
In my play framework project I have a confirmed functional Java map of the form Java that is passed to a html page home.scala.html
The map variable is passed in as other (working) variables are, at the top of the page:
#(workingVar1: String, workingVar2: Int, mapVar: Map[Long, Integer])
But developer tools in google chrome highlights this part of the javascript (embedded in home.scala.html's head):
var myMap = #mapVar;
With the error Uncaught SyntaxError: Unexpected token =
So none of the javascript works. What is the correct way to pass this map in?
You can use Java/Scala variables in Twirl Scala templates and both are executed on the server side.
Now on server side Twirl engine translates Java object to something (which probably isn't what you want) and in this form is passed to client, and then this JavaScript is executed.
You want to make sure that client will receive valid JavaScript code.
To assign proper value, you will have to mix some JSON libraries, which will help you assign value in a proper way.
Eg. on the controller side:
...
Map<Long, Integer> map = new HashMap<>();
map.put(1L, 2);
map.put(3L, 3);
String yourMap = Json.stringify(Json.toJson(map));
Now you want to pass yourMap to view, and then you will assign to myMap
using #Html as we want it as raw content fragment:
#(workingVar1: String, workingVar2: Int, mapVar: String)
var myMap = #Html(mapVar);
Try and let me know if it helped.
An inelegant but functional solution is as follows:
Bring in the Java Map as a string:
var stringMap = "#mapVar";
Removes the braces and spaces inserted into the string unnecessarily
stringMap = stringMap.replace(/{/g,'');
stringMap = stringMap.replace(/}/g,'');
stringMap = stringMap.replace(/ /g,'');
Split the mapString by , and for every pair split again by =, extracting keys and values as you go. These will need to be parsed to their correct data-types before adding to a javascript array jsArr:
var pairArray = mapString.split(",");
pairArray.forEach(function(pair) {
var values = pair.split("=");
var longString = values[0];
var intString = values[1];
var myLong = parseFloat(longString);
var myInt = parseInt(intString);
jsArr.myLong = myInt;
}
Where jsArr has been defined previously.
I want to put a JSON object into a javascript variable as a sting in order to create a graph.
qm.createGraphData = function() {
$.post("ajax_getGraphDataWebsite ", function(json) {
qm.negativesData = json;
},"json");
qm.data = [{
"xScale":"ordinal",
"comp":[],
"main":[{
"className":".main.l1",
qm.negativesData},{
"className":".main.l2",
qm.negativesData}],
"type":"line-dotted",
"yScale":"linear"}];
}
the string value should be added to the "data" section. Now the object get's added but I need to add the string value to the variable like the sample below:
{"data":[{"x":"3283581","y":"2013-10-16"},{"x":"1512116","y":"2013-10-17"},{"x":"3967","y":"2013-10-18"},{"x":"1094","y":"2013-10-19"},{"x":"853","y":"2013-10-20"},{"x":"1205","y":"2013-10-21"},{"x":"2618700","y":"2013-10-22"},{"x":"3928291","y":"2013-10-23"},{"x":"3670318","y":"2013-10-24"},{"x":"3347369","y":"2013-10-25"},{"x":"2525573","y":"2013-10-26"},{"x":"3224612","y":"2013-10-27"},{"x":"3992964","y":"2013-10-28"},{"x":"3949904","y":"2013-10-29"},{"x":"3568618","y":"2013-10-30"},{"x":"3104696","y":"2013-10-31"},{"x":"3246932","y":"2013-11-01"},{"x":"2817758","y":"2013-11-02"},{"x":"3198856","y":"2013-11-03"},{"x":"3952957","y":"2013-11-04"},{"x":"3934173","y":"2013-11-05"},{"x":"3878718","y":"2013-11-06"},{"x":"3642822","y":"2013-11-07"},{"x":"3186096","y":"2013-11-08"}]}
This would generate the right graph for me. Does anyone know how to convert the json object into a string like above and to send it to the qm.negativesData variable?
// UPDATE
Now I've got the string with the qm.negativesData = JSON.stringify(json); solution
But my qm.negativesdata won't get added to the qm.data variable... i'm getting a console error SyntaxError: invalid property id
I suppose i'm not adding them the right way?
To convert a JSON object into a JSON string, you can try myObject.stringify(), JSON.stringify(myObject), or if you are using a library using the built in function of that library.
So, you could do something like: qm.negativesData = myObject.stringify()
Cheers
I am encoding some model data into a html element like this:
#Html.Raw(Json.Encode(Model));
The json string returned looks like this:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
When I try to parse this using JSON.parse, I get an error:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
How do I convert this jsonTestList string into a javascript array so that I can access elements of arrayTestList properly?
Edit:
Sorry, I forgot to mention my edit. Basically above javascript code is inside a Partial View 2. The code where I am json encoding the model is in another Partial View 1. From P V 2, I cannot access the model object of P V 1, so I am just dumping the contents into a div tag, so that I can access this list TestList element.
Try removing this line:
jsonTestList = JSON.stringify(jsonTestList);
jsonTestList is already a JSON string
The issue is now resolved.
I was getting an invalid character, but couldn't immediately recognize which character it was that was causing the problem. I found that my JSON string isn't valid because of the trailing semicolon that was output by the Json.Encode method. I validated the JSON string # http://jsonlint.com.
Once I removed that semicolon, the json string is populated as a JavaScript array into arrayTestList object.
Now just this works, as mentioned in both the answers above, JSON.stringify is not needed.
var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]);
Why are you using Json.Encode? Also in your code, why are you writing redundant code first you are using JSON.stringify and the JSON.parse same object.
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
As per my understanding just Html.Raw will work
In JavaScript
var jsonObject = #Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList = jsonObject.TestList;
I'm trying to get the JSON object from a JSON outputted string from a Rails app. Currently in JavaScript I'm doing:
data = "<%= #chromosomes.html_safe %>";
However, since there are quotes at the beginning and end of the JSON object, it is not being rendered as a JSON object. Instead it is doing something like
data = "[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]"
Is there a way that I can remove the beginning and end quotes so that the object is treated as an array instead of a string?
Why don't you do:
data = <%= #chromosomes.html_safe %>;
Sidenote:
I hope you do something like:
#chromosomes = [{ name: "YHet", organism_id: "foo" }].to_json
If you are using jQuery you can do the following
var data = jQuery.parseJSON('[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]');
Use JSON object that is included in most of browsers or if you are using jQuery use $.jsonParse method that try to use JSON object if defined otherwise parse using eval or some safer way.
On controller
#my_var = MyObj.find_by_id(4).to_json
On page in haml way.
var my_json = $.parseJSON("#{j #my_var}"); //used JQuery to parser JSON string
Use eval:
var dataObject = eval('(' + dataString + ')');