how to send an object from spring controller to jsp through Ajax - ajax

I have a transaction object and I am trying to send the object to the front page. I have no problem when I try to send a string, but I couldn't send an object.
So this is my controller:
#RequestMapping(value="/result/helloajax", method=RequestMethod.GET)
#ResponseBody
public MyTransaction helloahjax() {
System.out.println("hello Ajax");
MyTransaction tran = MyTransaction.getInstance();
tran.setId(123);
return tran;
}
#RequestMapping(value="/result", method=RequestMethod.GET)
public String show() {
return "result";
}
and this is my ajax call
button
<div class="result"></div>
function doajax() {
$.ajax({
type : 'GET',
url : '${pageContext.request.contextPath}/result/helloajax',
success : function(response) {
$('.result').html(response.id);
},
error: function() {
alert("asda");
}
});
};
I search around and see that other developers used "response.result.id" but I couldn't make it neither. Any suggestion please.

I would suggest to change your code like below.
1.Include JSON library to your classpath and add produces="application/json" attribute to RequestMapping for the helloahjax method.
#RequestMapping(value="/result/helloajax", method=RequestMethod.GET,produces="application/json")
2.Include dataType in your ajax call,like below
$.ajax({
type : 'GET',
dataType : 'json',
url : '${pageContext.request.contextPath}/result/helloajax',
success : function(response) {
var obj = JSON.parse(response);
//Now you can set data as you want
$('.result').html(obj.id);
},
error: function() {
alert("asda");
}
});

The URL would change to below when you are returning JSON from the controller method. In this case you don't need to parse the response. Instead you can directly access the object variables as response.abc
${pageContext.request.contextPath}/result/helloajax.json

Related

ModelView, Ajax and Json return

In my code, i have two RequestMapper in my Controller which is designed this way :
#Controller
#RequestMapping("/myHostel.html")
public class HostelController
{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView getText()
{
// do some cool stuff but not the point here
}
#RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String getMyUrl()
{
String myVariable;
return "{\"myUrl\": \""+myVariable+"\""}";
}
}
And my ajax code :
function openNewTab() {
$.ajax({
url : 'myHostel.html',
type: "POST",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
},
success : function(response){
console.log(response);
window.open(response.url, '_blank');
},
error: function(jqXHR, exception, errorThrown)
{
console.log(jqXHR.status);
console.log(exception);
console.log(errorThrown);
}
});
}
and my button is kinda like this :
<button tabindex="0" id="mySweetButton" class="btn btn-primary"
onclick="openNewTab();" >
Open a new tab
</button>
And what i get is :
200
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
--
I've tried with putting a session variable in the model and a making a window.open(URL_IN_SESSION);
But if you reload the page, it's calling it again.
Making a c:remove on the variable when it's not used to cancel this problem but to no avail.
I have to get a variable from my ModelView after some previous call and open it in ajax (or javascript whatever as long as it works) to have my main page and my new tab with the custom URL.
If anyone has a idea on what i'm doing wrong ? (I need a custom URL made in my controller by previous GET call with user choices.)
Thank you for reading !
Solved by making just another GET requestMapping using no parameters and with value = ("/myHostel.html/getMyUrl.html")
One of the problem was the filters that only allowed .html url for the mapping.
The other was the JSON, just using :
#RequestMapping(method = RequestMethod.GET, value = "/getUrl.html")
public ResponseEntity<String> sendUrl()
{
return new ResponseEntity<>(getMyUrl(), HttpStatus.OK);
}
And parsing the return in ajax :
function openNewTab() {
$.ajax({
url : 'myHostel.html/getUrl.html',
type: 'GET',
dataType: 'text',
success : function(data){
window.open(data, '_blank');
}
});
}
And it solved the problem.

Sending data to MVC Controller with AJAX

I am trying to send data with AJAX to MVC Controller method, but I don't know what am I doing wrong.
Here is the AJAX call
$.ajax({
type: 'POST',
url: invokingControllerActionUrl,
data: "it is just a simple string",
success: function (data) {
window.location.href = link;
}
});
And here is the controller method. It is invoked, but the parameter is always null.
public IActionResult OnPostTest([FromBody] string stringValue)
{
// stringValue is always null :(
}
Change you ajax call to this
$.ajax({
type: 'POST',
url: invokingControllerActionUrl, // Confirm the Path in this variable Otherwise use #Url.Action("OnPostTest", "InvokingController")
data: {stringValue: "it is just a simple string"},
success: function (data) {
window.location.href = link;
}
});
And remove the [FromBody]. ALso its better to define type post. Not necessary though
[HttpPost]
public IActionResult OnPostTest( string stringValue)
{
// stringValue is always null :(
}
Depending on what Content-Type you are sending from JS, you might need to encode your string properly, as a form-value
...
data: 'stringValue="it is just a simple string"',
...
or e.g. JSON:
...
data: '{stringValue: "it is just a simple string"}',
...
See also this discussion
I haven't found an easy way to pass a string of unformatted data via parameter, unfortunately. According to this answer, you can do the following:
public IActionResult OnPostTest()
{
Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string stringValue = new StreamReader(req).ReadToEnd();
...
// process your stringValue here
...
}

JSP Catching Event from RadionButton

I am looking for something like onchange listener for radiobutton in JSP. I am using like this example:
https://www.tutorialspoint.com/springmvc/springmvc_radiobutton.htm
Anyone know how to catch the event of the radiobutton on the controller ??
There does not exist a default way to do this in Spring. Why exactly do you want to do this?
You basically would use an AJAX call to send the data of the selected button to the Rest Controller. Something similar to this pseudo-code.
jQuery(document).ready(function($) {
$("#your-buttons").change(function(event) {
event.preventDefault();
var data = formname.your-buttons.value;
$.ajax({
type : "POST",
contentType : "application/json",
url : "your/api/url",
data : JSON.stringify(data),
dataType : 'json',
success : function(data) {
display(data);
},
error : function(e) {
display(e);
}
});
});
});
Then on your Rest Controller you would simply have to handle it like any other event.
#RequestMapping(value = "/your/api/url", method = RequestMethod.POST)
public String whatever(.....) {
// ...
}

post ajax data to spring controller

I am a newbie to AJAX and i am trying to configure a simple method to post data into the controller using ajax only since i'm not sufficient in JSON
,lambda expressions other than Java can someone tell me what is the mistake i'm doing that this ajax method is not working?
Controller
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String addCart(int val1, int val2) {
System.out.println("+++++++++++++++++++++++++++++" + val1);
System.out.println("+++++++++++++++++++++++++++++" + val2);
return "redirect:/viewResult";
}
Ajax/Script
$(document).on('change', '._someDropDown', function (e) {
var x = this.options[e.target.selectedIndex].text;
var y = $(this).data('idtest');
alert(x);
alert(y);
$.ajax(
{
url: "/HRS/test",
data: {val1: x, val2: y},
method: 'POST'
});
});
note that these alerts(x and y values) are shown correctly.I just want to send them to my controller.Please any suggestions?
First of all you need to make your Controller accept a POST Request which your AJAX code would be sending.
Then you need to add a RequestBody Annotation over the POJO that you wish to accept from AJAX.
Let's say you need to send var x, y. Create a class like this:
public class MyData {
String x;
String y;
// getters/setters/constructor
}
Then you need to create MyData in your AJAX Call & pass it.
$(document).on('change', '._someDropDown', function (e) {
var myData = {
"x" : this.options[e.target.selectedIndex].text,
"y" :$(this).data('idtest')
}
.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/HRS/test", //assuming your controller is configured to accept requests on this URL
data: JSON.stringify(myData), // This converts the payLoad to Json to pass along to Controller
success :function(result) {
// do what ever you want with data
}
});
Finally your controller would be something llike:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public #ResponseBody String addCart(#RequestBody MyData data) {
System.out.println(data.getX());
System.out.println(data.getY());
return something;
}
My knowledge is a bit rusty but I hope you get the idea how this works!

How to use ajax in asp.net MVC

How can I return a class object from Ajax in asp.net MVC....???
Example:
Ajax call from html:
$.ajax({
type: 'POST',
url: '/Tutorial/Web/AlignmentRule/GetAlignmentDetails',
data: { alignmentRuleId: alignmentRuleId },
success:
function (data) {
alert(data.Id);
alert(data.alignmentData.Id);
$("#ruleName").val(data.alignmentData.Name);
$("#level").val(data.alignmentData.Id);
},
error:
function () {
alert("Server Error!!!!");
},
dataType: 'JSON',
async: false
});
and Action method in contorller is:
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData );
}
And I want to return a list of alignmentRule class objects also....
you can compose your return object as you want, for example, create a ViewModel as decorator to hold everything you want to pass, like:
var json = new JsonViewModel() {
alignmentData = alignmentData,
rules = yourRules
};
return Json(json);
The error is thrown because by default MVC framework does't allow you to respond to an HTTP GET request with a JSON (because of security reasons).
In order to make it work, when you retrurn Json in your action, you need to specify JsonRequestBehavior.AllowGet
[HttpPost]
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData, JsonRequestBehavior.AllowGet);
}
EDIT
Annotate your action with [HttpPost] attribute.
For further investigation on this topic check this article

Resources