How to get spring mvc controller model key value inside javascript? - 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

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>

Pass a dictionary from Djanjo view to another view via 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>

Using C# object in razor view page

I have this rows of c# code in View razor page:
#{
List<UserContact> userContacts = ViewBag.contacts;
String contacts = Html.Partial("~/Views/Shared/Contacts.cshtml", userContacts).ToHtmlString();
}
I want to use the content of contacts variable in JavaScript function since the contacts is a C# object I cant use this variable in JavaScript function.
Is there any way to use contacts variable in Javascript function?
Maybe since the type is string it can be converted to JavaScript variable?
You can use # directives like you would normally do. You can print it using Html.Raw:
var x = /* this is javascript */
#{
...
#Html.Raw(contacts)
}
Or just call #Html.Partial directly:
var x = /* this is javascript */
#{
...
#Html.Partial(...)
}
Or declare it here:
#{
...
string contacts = #Html.Partial(...)
}
And use it later:
#contacts
Yes there is, you only need to render it inside a script block. Try this:
<script>
var contacts = '#contacts';
alert(contacts);
</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 access a variable in a function from inside a jsp tag

I have the following function:
<script>
function assign()
{
var val = "";
val = document.form1.text1.value;
alert(val);
}
I want to access the variable val's value inside jsp tag so that i can pass it to the googlePlus method as a String. I tried making var val as a global variable, but it doesnt work. How can I access the variable val inside the following code?
<%
String output = "";
if ( Boolean.valueOf(request.getParameter("submitted")) == true ) {
Scraping h = new Scraping();
output = h.googlePlus();
}
%>
You can assign the value of the variable using a assignment operator to some hidden JSP field and then use it in the JS using document.getElementById(). the code would be somewhat like:
<input type="hidden" value="<%=output%>">
Or alternatively if your js is residing inside the JSP only
var s = "<%=output%>"; should work!
Cheers!
You can't access javascript variables via JSP Java Code.
Your JSP & Java codes are compiled at server side.
And your javascript runs in a browser.
So send the 'val' variable to your servlet by form submit, ajax or whatever.

Categories