Pass a dictionary from Djanjo view to another view via javascript - javascript

I have a view that passes a dictionary (along with a couple of forms and strings) to an HTML template. The template has a js file. I am accessing the dictionary in js like this:
<script type = "text/javascript">
var request_dict = {{request_dict|safe}};
</script>
Now, I want to pass this on to another view via POST(not necessarily, it can change). The format of request.POST in second view should be like a dictionary inside a dictionary. But the dictionary(request_dict) comes as a list instead of a dictionary.
How can I resolve this? Do I have to use JSON? Please mention if my explanation is wierd.

Use JSON, its safe.
View:
retutn render(request, 'template.html', {
'request_dict': json.dumps(request_dict),
}
Templete:
<script type = "text/javascript">
var request_dict = JSON.parse('{{request_dict|safe}}');
</script>

Related

NODE.JS accessing functions within an EJS template

I have a scripts.js file that includes a function inside that i want to access within an EJS templates.
in the templates i included a header, in the header I added a script rel to scripts.js
<script src="/scripts/scripts.js" type="text/javascript"></script>
I tested it though console.log("test") and when the template is being called I see "test" appears in the console.
when I try to call an actual function (verify_data) within the EJS template i get an error verify_data is not defined.
the error code within the EJS looks like this:
<p><em>Submited By <%= verify_data(results.user.username) %></em></p>
the function check if the argument passed is null/undefined, if yes the data returns if not "n/a" string returns instead.
How do i access JS functions directly within EJS template ?
Thanks,
Assuming you're not using a SPA framework, you need to add a tag which will be either replaced by the function or to contain the data you want to store.
Look at this code snippet
<p><em>Submited By <span id='userData'></span></em></p>
<script>
//This is the script.js
function verify_data(userName) {
return `My data with '${userName}'`;
}
</script>
<script>
let data = verify_data("EleFromStack"); // assuming <%=results.user.username%> = "EleFromStack"
document.querySelector("#userData").textContent = data;
</script>

How to use Parameters passed to Partial view in a separate javascript file

I have a Partial view which takes in parameters and displays a Markdown Editor based on the parameters passed.
#Html.Partial("_MarkdownEditor", new { id = "fieldsection" })
<div id="#ViewData.Eval("id")"> </div>
<script type="text/javascript">
var #ViewData.Eval("id") = new tui.Editor({
el: document.querySelector('##ViewData.Eval("id")')})
</script>
In the source code of the tui.Editor i have a Ajax call to a controller something like this..
$.ajax({
url: 'Home/Index',
success: function (data) {
editor.importManager.eventManager.emit('command', 'AddImage'})
Here the problem is with this line..
editor.importManager.eventManager.emit('command', 'AddImage)
Here in the place of editor i need to reference the parameters passed to Partial view..it should be like this:
fieldcomments.importManager.eventManager.emit('command', 'AddImage)
It should be done dynamically i have tried something like..
{#ViewData.Eval("id")}.importManager.eventManager.emit('command', 'AddImage)
But this doesn't work like this? How can i reference the Parameters passed to Partial view in a separate javascript file??
You can make the variable global in the view where you can still access #ViewData.Eval("id"). Like this answer
Example:
<script> var a = #ViewData.Eval("id") </script>

Passing Dictionary from controller to Javascript

I have a view model like this:
public class weightdata
{
...some properties
public string weights;
}
Then, I have in the controller:
weightdata details = new weightdata();
Dictionary<string,float> dict = new Dictionary<string,float>();
//do something to fill the dictionary with values
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
details.weights = ser.Serialize(dict);
return View(details);
Then in the view:
<script type="text/javascript">
var dict = #{Html.Raw(new JavaScriptSerializer().Deserialize<Dictionary<string,float>>(Model.Weights));}
</script>
But the rendering of the page is:
var dict = (it's blank)
How can I get this dictionary of values into where it can be used by javascript?
Your property is already serialized, meaning it's already JSON. You don't want to deserialize it on the view, just write it out directly:
var dict = #Html.Raw(Model.Weights);
The other alternative is to make your property a Dictionary<string, float> instead of a string, then you would serialize it on the view:
var dict = #Html.Raw(new JavaScriptSerializer().Serialize(Model.Weights));
Something I just recently read about which may make your view a bit cleaner - you can actually dump the JSON into its own script tag with type="application/json", and reference it in javascript. This may make your editor a little happier, since it's easier to separate the javascript from the C# code.
Something like:
<!-- assuming your Weights property is the serialized JSON string -->
<script id="some-json" type="application/json">
#Model.Weights
</script>
<script type="text/javascript">
var dict = JSON.parse(document.getElementById("some-json").innerHTML);
</script>
Just make sure you're targeting IE8+ or a real browser - if you need IE7 support, you'll need something like json2.js.

How to get spring mvc controller model key value inside javascript?

I am using a spring mvc controller. Inside controller i am putting some value lets say string inside model. Now i would like to retrive that value or lets just say print that value inside a javascript. How do i do it?
Here is my controller class. I am adding "movie" as key. Now i want to display that name of the movie inside java script (Not inside JSP. However Inside JavaScript)
#Controller
#RequestMapping("/movie")
public class MovieController {
#RequestMapping(value="/{name}", method = RequestMethod.GET)
public String getMovie(#PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return "list";
}
}
here is my JSP
<html>
<head>
//I want to print movie name inside java script not inside jSP body tag.
<script type="text/javascript">
var movie_name = ${movie};
alert("movies name"+ movie_name);
</script>
</head>
<body>
<h3>Movie Name : ${movie}</h3>//When i print here its working fine.
</body>
</html>
Use this:
var movie_name = "${movie}";
instead of:
var movie_name = ${movie};
When using ${movie}, the value gets placed on the page without quotes. Since I'm guessing it's a string, Javascript requires strings be surrounded by quotes.
If you checked your browser's console, you probably would've seen an error like Unexpected identifier or ___ is not defined.
Try this...
If you had added the object into the model as:
model.addAttribute("someObject", new Login("uname","pass"))
Then you get the properties of the model object as
var user_name = ${someObject.uname}; // This is assuming that the Login class has getter as getUname();
var user_pass = ${someObject.pass};
<html>
jsp code ...
<script>
some js code ..
..
var formProperty = <c:out value="${fromBean.property}" />
</script>
..
</html>
This worked for me where formBean is the name of form backing object and property is filed of the form class

Can I Pass a JS Object or Reference to a JS Object to a Function in the HTML Markup?

Pretty noobish question, and I'm probably thinking about this wrong, but...
Is there a way to pass a javascript object (or a reference to it) to a javascript function within the HTML markup?
For example:
<script type="text/javascript">
var myObject = new Object();
$('body').append('<div onclick=testThis(' + myObject + ')></div>');
function testThis(object)
{
console.log(object);
}
</script>
The markup ends up looking something like this when I inspect it:
<div onclick="testThis([object Object])">
Additional context:
The real use case is a search page in which I am querying SOLR via AJAX and get a result back as JS objects. When the user clicks on the HTML markup representing one of these search results, I want to be able to pass the object(or a reference to it) to a separate JS function for processing.
Am I thinking about this the wrong way?
No, you can't embed a reference to an object into markup.
Instead you probably would like to setup your click event listening in Javascript/jQuery:
var object = new Object();
$('<div/>').appendTo('body').click(function() {
testThis(object);
});
function testThis(value) {
console.log(value);
}

Categories