How to handle variable from Spring controller using javascript? - javascript

Guys i have problem to get data from variable after execute rest in my controller. Here is sample to show my problem.
Controller
#RequestMapping(path = "/editSchema/{id}")
public String editSchemaById(Model model, #PathVariable("id") Integer id)
{
model.addAttribute("message", "why this isn't working...");
return "redirect:/drawdiagram";
}
JavaScript drawdiagram.html
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
/*]]>*/
</script>
Result
Anyony can tell me why i have null there?
I really don't know what is going on :(
Maybe this is bad way? I have chosen thymeleaf but maybe there is some other way?
All i need to do is:
1. Click button.
2. Execute some backend code and get data to variable in controller.
3. Redirect to other page.
4. Execute some JavaScript code which is based on that variable.
.
Sources:
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart
Setting up a JavaScript variable from Spring model by using Thymeleaf

you are redirecting to another controller drawdiagram, the values in model object won't be available in other controller. So here you need to set the value first using either RedirectAttributes#addFlashAttribute or RedirectAttributes#addAttribute, and then get the value in the other controller -using #ModelAttribute("message").
#RequestMapping(path = "/editSchema/{id}")
public String editSchemaById(Model model, #PathVariable("id") Integer id, RedirectAttributes redirectAttributes)
{
redirectAttributes.addFlashAttribute("message", "why this isn't working...");
return "redirect:/drawdiagram";
}
#RequestMapping(value = "drawdiagram", method = RequestMethod.GET)
public String OtherController(#ModelAttribute("message") String message, Model model) {
model.addAttribute("message", message);
return "drawdiagram";
}

Related

on page load call controller method using data from query string

Is it possible to retrieve query string data on page load using javascript?
Let me explain my sample project in steps::
I have a view page showing tabular data. On button press, it retrieves id of the row and calls javascript function.
This javascript function, getDetails(id) has to call another view page, say Application.cshtml.
I have to pass the value of id and a variable message to this view page Application.cshtml.
I am trying to pass this as query string.
Now in this view page Application.cshtml, I have to retrieve the value of id and call contoller method to show the details of the id on page load.
Is it possible to do using javascript?
function getDetails(id)
{
var message = "testing";
var id_ = id;
window.location = "/FirmModels/Application/" + id_;
}
My problem is how can I retrieve the value of id and call controller method on page load using javascript in Application.cshtml?
Your question is a bit unclear but as far as I understood this question you can do this in two ways.
Assuming that you have something like this in your JS file.
window.location = "/Controller/Application?id= " + id_;
In the first method, the View inside your Controller will look like this
public ActionResult Application()
{
string id= Request.QueryString["id"];
//Do your operations here
return View();
}
The second way to do this to pass the id as a mandatory parameter to the view.
public ActionResult Application(string id)
{
return View();
}

How to get value from spring controller class in javascript?

I have a controller class in spring. I am passing values such as a simple string or a hashmap. I know how to get values in thymeleaf. I want to get values on my html page in pure javascript, no thymeleaf. My controller class :
String s="RUSSIA";
#RequestMapping(value = "/", method = RequestMethod.GET)
public String Country( Model model) {
model.addAttribute("country", s);
return "index";
}
Now I want to get this string in javascript variable. I am using HTML not JSP.
You could do something like this:
<script th:inline="javascript">
/*<![CDATA[*/
var country = [[${country}]];
console.log(country);
/*]]>*/
</script>
If you want to run your html offline you can do this, and the JS variable will be always the fixed value of Russia
var country = /*[[${country}]]*/ 'Russia';

In spring mvc how do I get a javascript var as parameter in a java function?

I'm working on a jsp page and I need a Javascript variable as parameter inside a java function e.g.:
<script>
function example(string){
<% javaFunction(string); %>
}
</script>
how can I pass the javascript String variable to the java fucntion?
DONT USE SCRIPTLETS IN JSP!.
You must understand jsp (views) code is executed in client side, java one is at server (host) one.
In order to get variables from the host side, you have plenty vays, but for small things best option is to make an ajax call:
$.get( "javaFunction",
{ variable: "VALUE" }
).done(function( data ) {
alert("Java function returned " + msg);
});
In java you need to map the url:
#RequestMapping(value = "/javaFunction", method = RequestMethod.POST)
public
#ResponseBody
String javaMethod(#RequestParam("variable") String variable) {
if (variable.equals("VALUE") {
return "Correct call!";
} else {
return "Mistake!";
}
}

Send an array using javascript to Spring controller

I´m making a call using javascript and I would like to send an array:
var selected = [];
selected=getAllEnginesIdsSelected();
console.log("selected: "+selected);
$.getJSON('/call/' + selected,
function(myList) {
Console.log retrieves selected: 2,5
In MVC Controller I have
#RequestMapping(method = RequestMethod.GET, value = "/call/{selected}")
public List<List<myList>> myCall(#RequestParam(value="selected[]") String[] selected){
I gives an error. I don´t want to use AJAX. This is posible to send?
EDIT
The funcion that I use in Javascript to retrieve array is:
function getAllEnginesIdsSelected() {
var selected = [];
$("input:checkbox[id^='engine_']:checked").each(function(){
var ele=$(this)[0].id;
});
return selected;
}
I guess you should use #PathVariable instead of #RequestParam in your controller.
You can get all the request parameters you send to spring controller by using:
#RequestParam Map<String,String> allRequestParams
You need to assign a name to each parameter to retrieve them later:
?a=1&b=2&c=3
Another way is to serialize your data and send a POST request to the controller.

send java script function parameter to ASP.NET MVC helper method

I have a Ajax form in my asp.net mvc application, which has a onSuccess callback as below:
function onSuccessReport(context)
{
$('reportChart').empty();
var line1=#Html.GetStrippedString(context.Expenses);
}
I defined a html helper which accept an string an manipulte it and return a string.
What I pass to onSuccessReport, is a json result which has a structure like this:
But I cant send context.Expenses and the application throws syntax error.
How can I send a javascript variable to my helper?
Thanks
Edited:
The error in my view
****Error 1 The name 'context' does not exist in the current context****
C# method
json = json.Replace("\"Date\":", string.Empty);
json = json.Replace("\"Total\":", string.Empty);
json = json.Replace('}', ']');
json = json.Replace('{', '[');
return MvcHtmlString.Create(json);
You are mixing client side code (javascript) with server side code (HtmlHelper). You cannot pass client side variables to server side helpers. If the context variable is known only on the client then you will have to write a client side javascript function instead of server side helper. So move to logic you wrote in this Html.GetStrippedString helper into a javascript function that you could call from your script.
Actually, you can send javascript values over to the server side if you use Ajax. Instead of using your helper method the way you are, just change it into an action within the Controller to return you some Json (could just be a string, number, object, etc, etc). Here is an example of what you might try out.
View
function onSuccessReport(context)
{
$('reportChart').empty();
var expenses = context.Expenses;
$.getJSON('#Url.Action("GetStrippedString", "ControllerName")', { expenses: expenses }, function (data) {
//pending what you pass back as data, do whatever with it
alert(data);
});
}
Controller
public JsonResult GetStrippedString(string expenses)
{
var result = string.Empty;
//Do something to string
return Json(result, JsonRequestBehavior.AllowGet);
}

Categories