ajax call from view to controller in Play framework - model-view-controller

I am newbie to MVC and Play framework (Java). Instead of using Groovy for dynamic HTML, I made our own page with static HTML, I mean we haven't any Groovy expressions. Here, I have a controller "Customer", generates JSON object which has to be sent to an ajax call in view. I tried with render() method, seems I haven't used correctly. can you give me some idea to forward from here. thanks.
public static void customer(){
WordAPI objWordAPI=new WordAPI();
List<WordInfo> listObjWord= objWordAPI.MakeAPIObject(nSurveyId);
JSONSerializer modelSerializer=new JSONSerializer().exclude("NSpontanity","NWordRepresentativity","NWordValue","NWordFrequency","class").rootName("Words");
render("Application/wordcloud.html",modelSerializer.serialize(listObjWord));
}
and ajax call in view "wordcloud.html"
$.ajax({
url: "/customer",
dataType : 'json',
success: function (data) {
alert(data);
}
})

I believe this should work:
public static void customer(){
WordAPI objWordAPI=new WordAPI();
List<WordInfo> listObjWord= objWordAPI.MakeAPIObject(nSurveyId);
JSONSerializer modelSerializer=new JSONSerializer().exclude("NSpontanity","NWordRepresentativity","NWordValue","NWordFrequency","class").rootName("Words");
renderJSON(modelSerializer.serialize(listObjWord));
}
I've never used rootName before, I usually just do something more like this:
public static void refreshNotifications()
{
JSONSerializer notifySerializer = new JSONSerializer().include("message","notifyId","class").exclude("*");
List<Notification> notificationList = user.getNotifications();
renderJSON(notifySerializer.serialize(notificationList));
}
Side Note: With refreshNotifications I have a Security method I run before which verifies and populates the user object.

Related

Listen to input field using a spring controller

Is it possible, in our controller, to get realtime input from a user writing in a html textfield? I know its possible to do via eg. jquery/js, but we are students and want a java'ish solution.
only using java is impossible because java need communication with the HTML page, you can perform that but you need to use java-script too. for example you can write a controller and call it using Ajax in a event java-script method like keyup.
#RestController
#RequestMapping("/info/")
public class Controller {
#RequestMapping(value="/get/",
method=RequestMethod.POST,
produces=MediaType.APPLICATION_JSON_VALUE,
consumes=MediaType.APPLICATION_JSON_VALUE)
public Map<String,Object> getInputData(#RequestBody Map<String, Object> data){
String inputData = data.get("inputValue").toString();
//TODO
return data;
}
}
from java-script build your Json response and call /info/get/ rest URL.
for example using axios.
axios.post('/info/get/', {
inputValue: 'your input form data'
})
.then(function (response) {
//todo
})
.catch(function (error) {
// if has errors
});
but otherwise can't be

How to receive multiple Data in controller side using FormData(Ajax)?

My ajax has used FormData and append multiple Field value (like Text-box,label,File) in single(FormData) object. and i have posted that data at server side but
How to receive same data object in controller?
FormData variable :
var uploadFile = new FormData();
var files = $("#UploadFile").get(0).files;
if (files.length > 0) {
uploadFile.append("Doc", files[0]);
}
FileUpload(uploadFile);
Javasacript method Ajax Call :
function FileUpload(uploadFile)
{
var url = '#Url.Action("UploadCsvFile")';
$.ajax({
url:url,
contentType: false,
processData: false,
data:uploadFile,
type: 'POST',
success: function () {
alert("Successfully Added & processed");
}
});
My Question is....if in case,My ajax has more Data, How to receive the same data in controller side and what, if i want to use specific Data object.
You can receive customized forms that are quite complex
It will work in two parts:
Part 1 - Extending the html FormData:
uploadFile.append("TextData", "This is my text data");
Part 2 - Extending your controller:
I assume your model would look something like this:
public class MyModel
{
public HttpPostedFileBase Doc{ get; set;}
}
Now just add your custom data to it:
public string TextData {get;set;}
And in your controller method:
public JsonResult MyUploadMethod(MyModel model)
{
/*From here you will have access to the file and the text data*/
}
Hope it helps. Ask me any questions if you need help.

How to map Bootstrap Modal to Spring MVC controller

I have a form in Bootstrap Modal and I want my Spring MVC controller to listen that. My problem is that the modal doesn't generate href because it's inside current page so I can't map just the modal in my Spring MVC controller.
I need it, because I want to show errors from bindingresult object. How can I do this?
This is my modal: http://www.bootply.com/zerZIYpNAF Let's say it's located in index.jsp so imaginary path would be /index#myModal.jsp or something like that.
#RequestMapping(value="/send", method = RequestMethod.GET)
public String get(Dummybean bean){
return "??"; //index#myModal
}
#RequestMapping(value="/send", method = RequestMethod.POST)
public String post(#Valid #ModelAttribute("dummy") DummyBean bean, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "??"; //index#myModal
}
//do something
}
public class DummyBean{
#NotNull
private String name;
public String getName() {
return username;
}
public void setName(String name) {
this.name = name;
}
You can't directly call the bootstrap modal to pop up by using controller. There for you will not able to bind form with Spring. But you can Achieve it using Ajax. You have to use form like normal Html form without using spring tags.
function searchAjax() {
var data = {}
data["query"] = $("#query").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "${home}search/api/getSearchResult",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
This is an example ajax for you to get an idea. You have to HttpServletRequest to retrieve data from controller side. Above example is taken from http://www.mkyong.com/spring-mvc/spring-4-mvc-ajax-hello-world-example/
1) create new function just for validation
2) create js function using prefer to use jquery and send ajax request to function in step one.
3) depend on validation status will handle errors or send form completely.
please read this article it's fully answered your question
javacodegeeks.com

JObject parameter is null in WebApi Action

I have an api controller action that takes a JObject as a
public class ThemeController : ApiController
{
[HttpGet]
public String Get(String siteName, JObject lessVariables)
{
and an ajax call
$.ajax({
url: '/api/Theme/Get',
data: { lessVariables: JSON.stringify({'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}), siteName: "UnivOfUtah" }
});
When I look at HttpContext.Current.Request.Params["lessVariables"] it gives the correct string of json, but lessVariables is an empty JObject. Is there something else I have to do to setup Json.Net for this?
I've also tried it on a regular controller action
I have a controller action that takes a JObject as a
public class ThemeController : Controller
{
[HttpPost]
public String Post(String siteName, JObject lessVariables)
{
and an ajax call
$.ajax({
url: '/Theme/Post',
data: { lessVariables: JSON.stringify({'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}), siteName: "UnivOfUtah" }
});
same result
The problem is that lessVariables is now a String. The whole structure probably looks like:
{
"lessVariables": "{'brand-primary': '#222222','brand-success': '#222222','brand-danger': '#222222','brand-info': '#222222','btn-primary-color': '#222222'}",
"siteName": "UnivOfUtah"
}
This is why you can see the correct string in the Params, but the framework is not able to convert it to JObject without knowing it is Json. When you Stringify the root object of a request, WebApi is smart enough to take it as Json as a whole, but you stringified a value inside so it has no idea it should be handled as json.
To fix it, you can either do custom binding with a model binder or custom action, or simply change your method to:
[HttpGet]
public String Get(String siteName, String lessVariables)
{
JObject jo = JObject.Parse(lessVariables);
Update:
To make the issue clearer, this is parsed fine by WebApi, but lessVariables is still a string:
[HttpGet]
public String Get(JObject rootObject)
{
// you now have rootObject which has a "siteName" and "lessVariables" parameter
var siteName = rootObject.GetValue("siteName");
var lessVariables = rootObject.GetValue("lessVariables");
// lessVariables.Type would return the JTokenType String

How To Pass formdata parameters into ASP.NET WebAPI without creating a record structure

I have data coming into my form that looks like the image below (sessionsId: 1367,1368).
I've create c# in my webapi controller that works as below. when I've tried ot just make use SessionIds as the parameter (or sessionIds) by saying something like PostChargeForSessions(string SessionIds) either null gets passed in or I get a 404.
What is the proper way to catch a form parameter like in my request without declaring a structure.
(the code below works, but I'm not happy with it)
public class ChargeForSessionRec
{
public string SessionIds { get; set; }
}
[HttpPost]
[ActionName("ChargeForSessions")]
public HttpResponseMessage PostChargeForSessions(ChargeForSessionRec rec)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new ShirtSizeReturn()
{
Success = true,
//Data = shirtSizeRecs
});
return response;
}
You can declare the action method like this.
public HttpResponseMessage Post(string[] sessionIds) { }
If you don't want to define a class, the above code is the way to go. Having said that, the above code will not work with the request body you have. It must be like this.
=1381&=1380

Resources