Pass Spring model attribute to JS script - javascript

So, I'm having my data parsed to json and then put in the model attributes. Like this:
#RequestMapping("/{id}")
public String getNetworkDetails(Model model, #PathVariable String id) throws JsonProcessingException{
model.addAttribute("poolHashrates", findAndDisplayDataService.getAllPools(Long.valueOf(id)));
model.addAttribute("poolDataJson", findAndDisplayDataService.returnPoolsAsJson(Long.valueOf(id)));
return "networkDetails :: modalContents";
}
Next I'm trying to assign a poolDataJson string to a JS variable in html fragment through:
<script>
var data = eval('('+'${poolDataJson}'+')');
console.log(data);
</script>
What I would like to do with the data, is pass it to external JavaScript file as a data for my pie-chart. But first I'm getting an error on a string assignment:
Uncaught SyntaxError: Unexpected token {
What am I missing?
EDIT
I have also tried assigning json string to hidden input via:
<input type="hidden" id="networkId" th:value="${poolDataJson}"/></td>
And then read it with:
var data = document.getElementById('networkId').innerHTML;
console.log(data);
But again, nothing prints in console. When I put the ${poolDataJson} in it prints properly on a page...

You shouldn't be returning a String as JSON text. Instead, you should return regular Java objects and then evaluate it like this (thymeleaf will automatically convert objects to JSON):
<script th:inline="javascript">
var data = /*[[${poolDataJson}]]*/ {};
console.log(data);
</script>
As for your errors. I would have to guess that your method findAndDisplayDataService.returnPoolsAsJson is returning invalid JSON. Without a real example, it's hard to tell.

Related

ASP.NET Core ViewData access in javascript

I am sending a filepath ( string) from controller to html page through ViewData and I want to access that string in my javascript, consume it, run some algo in javascript and then use results to consume them and make some graphs on the same html page.
HTML
</head>
<body>
<div id="mychart"></div>
<script>
var path=#ViewData["path"];
//some javascript logic with the string path of the file.
//using results for output chart of id 'mychart'
</script>
</body>
</html>
Controller Action Code:
public IActionResult CellResult(string outputpath)
{
ViewData["path"] = outputPath;
return View();
}
Since it is a string value, you need to wrap it in either single quotes or double quotes.
var path='#ViewData["path"]';
alert(path);
EDIT : As per the comment
How can I send a list of string from controller to html page and use
it in javascript? instead of string i wanna send a list of string
If you want to send a list of string, it is the same, but since it is a complex type now, you need to use the json serializer to convert this object to a string.
So in your server
var list = new List<string> {"Hi", "Hello"};
ViewBag.MyList = list;
and in the view
<script>
var list = #Html.Raw(JsonConvert.SerializeObject(ViewBag.MyList));
console.log(list);
</script>

recieving broken JSON data in javascript

I have PageMethod in javascript which is receiving JSON data from C#.
In C# its getting full xml data from database and converting into JSON and sending back to PageMethod.
JSON Converted data is about 33kb, but i'm not able to receive full data in javascript. I'm receiving only 9 kb of data. any solution for getting full data in java script.
PageMethod.methodName(onSuccess,OnFail);
function OnSuccess(result)
{
alert(result);
}
function OnFail()
{
alert("Error");
}
C# code as follows,
ParamResult objParamResult = new ParamResult();
objParamResult.ResultDt = string.Empty;
DataTable XmlMainSub = objCBTag.getParamPickupDetailsDB();
string myData = XmlMainSub.Rows[0][0].ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(myData);
string jsonText = JsonConvert.SerializeXmlNode(doc);
return jsonText;
instead of
string jsonText = JsonConvert.SerializeXmlNode(doc);
you can use
string jsonText = new JavaScriptSerializer().Serialize(doc).toString();
you need to use namespace for this
using System.Web.Script.Serialization;
After i made lot of research, i found that its not possible to send JSON data from C# to javascript which is more than 8KB or 9KB in size.
And i solved this problem by making use of c# generics which is Dictionary which contains Key and Value Pair. I Tried to loop XML Data which is coming from database and stored in a dictionary object.
Then i passed it to javascript. There i able to receive full data without any error.

save parsed JSON as obj

first question ever, I'm trying to parse a JSON file stored within the same file directory on my webhost as my html file that runs the javascript to parse it, I've added a console.log to debug and confrim that the file is being caught by the 'get' to ensure that I am able to 'get' the file throgh the use of jquery getJSON, in the callback i've tried to create a function that re-defines a global variable as an object containing the parsed data, but when I try to inject it into a document.getElemendtById('example').innerhtml = tgmindex.ToughGuys[1].name;
it returns a error "Uncaught TypeError: Cannot read property '1' of undefined"
here's my js/jquery
var tgmIndex;
$(document).ready(function () {
$.getJSON("http://webspace.ocad.ca/~wk12ml/test.json",function(data){
console.log( "success" );
tgmIndex =$.parseJSON;
document.getElementById('tgm1').innerHTML= tgmIndex.ToughGuys[1].name;
});
});
and here is whats contained in the JSON (i made sure to try linting it first and it's a valid json)
{"ToughGuys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":" original Intern"}
]}
You're setting tgmIndex to the parseJson function.
Should be doing tgmIndex =$.parseJSON(data);
Presumably your service is returning application/json. Therefore data already contains the json.
tgmIndex = data;
Then... "Tough Guys" is what you should be indexing. Not "ToughGuys"
Your example JSON is wrong in your question. If I go to
http://webspace.ocad.ca/~wk12ml/test.json
I see:
{"Tough Guys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":"Intern 0"}
]}
See "Tough Guys" There's your problem.
document.getElementById('tgm1').innerHTML= tgmIndex['Tough Guys'][1].name;
If data for some reason isn't JSON:
tgmIndex = $.parseJSON(data);

Safely Using JSON with html inside of the JSON in Django Templates

How do you safely render JSON data in a django webapp?
On the server in django I generate JSON data and then render that JSON data in a django template. The JSON occasionally contains snippets of html. Most of the time, that's fine, however if the </script> tag is inside the JSON data when it is rendered, it destroys the surrounding javascript.
For example...
On the server, in python I'll have this:
template_data = {
'my_json' : '[{"my_snippet": "<b>Happy HTML</b>"}]'
}
# pass the template data to the django template
return render_to_response('my_template.html', template_data, context_instance = c)
And then in the template:
<script type="text/javascript">
var the_json = {{my_json|safe}};
</script>
... some html ...
The resulting html works fine and looks like this:
<script type="text/javascript">
var the_json = [{"my_snippet": "<b>Happy HTML</b>"}];
</script>
... some html ...
However, you run into problems when, on the server, the JSON looks like this:
template_data = {
'my_json' : '[{"my_snippet": "Bad HTML</script>"}]'
}
return render_to_response('my_template.html', template_data, context_instance = c)
Now, when it's rendered, you'll get:
<script type="text/javascript">
var the_json = [{"my_snippet": "Bad HTML</script>"}];
</script>
... some html ...
The closing script tag within the JSON code is treated as closing the entire script block. All of your javascript will then break.
One possible solution is to check for </script> when passing the template data to the template, but I feel like there is a better way.
Safely insert the JSON as a string, and then call JSON.parse on it
Use escapejs instead of safe. It is designed for outputting to JavaScript.
var the_json = '{{my_json|escapejs}}';
To get a JavaScript object you then need to call JSON.parse on that string. This is always preferable than dumping a JSON-encoding into your script and evaluating it directly, for security reasons.
A useful filter to get python objects directly to the client that I use is this:
#register.filter
def to_js(value):
"""
To use a python variable in JS, we call json.dumps to serialize as JSON server-side and reconstruct using
JSON.parse. The serialized string must be escaped appropriately before dumping into the client-side code.
"""
# separators is passed to remove whitespace in output
return mark_safe('JSON.parse("%s")' % escapejs(json.dumps(value, separators=(',', ':'))))
And use it like:
var Settings = {{ js_settings|to_js }};

Accessing JSON values with a variable

I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.
My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:
{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}
I then have a function which is essentially this:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}
}
But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.
Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.
The data access itself works for me:
var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA
Make sure that attrib remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.
Update: is this your real code? You have at least one syntax error:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}); // <- Please note missing ");"
}
In my experience, $.getJSON() doesn't always return an object. Depending on the MIME type that the server returns along with the JSON, you might end up with a string instead of an object. Check what data contains. If it's a string, you must manually parse it using eval() (old style) or JSON.parse() (new browsers only).
try to list all properties from data, to have sure the data is being returned:
for (var p in data){
if (data.hasOwnProperty(p){
alert(data[p]);
}
}
It's not your solution but with this you can know how your data is coming.

Categories

Resources