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(.....) {
// ...
}
Related
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.
I'm trying to pass a serialized form and an array through a single ajax call. I'm getting an error everytime I submit. I want to receive both in my controller and I have no idea how to do it. This is my code based on other tutorials I found online but it doesn't work.
ajax call:
var o = Array.prototype.slice.call(document.getElementsByName("client_beneficiary[]")).map(e => e.value);
$.ajax({
url: "/SaveProductApplication",
type: "post",
data: {
$("#product_form").serialize(),
beneficiary_list: o
},
success: function() {}
});
controller:
#RequestMapping(value= "/SaveProductApplication", method=RequestMethod.POST)
public #ResponseBody boolean save(ProductApplication productApplication, #RequestParam(value="beneficiary_list[]") String[] beneficiary_list) {
for (String arrElement : beneficiary_list) {
System.out.println("Item: " + arrElement);
}
}
hoping you could help me. thank you!
I am trying to do an ajax request and depending on the ajax request results I will allow the form to submit to the controller. However everytime the ajax request runs I get the error message.
Here is my javascript function:
function CheckForValidation(e) {
var scholarshipRequest = $("#scholars").val();
var aidYearRequest = $("#aidYear").val();
var amountRequest = $("#amount").val();
$.ajax({
type: "POST",
url: '#Url.Action("Validate_ScholarshipRequest", "RequestController")',
data: {
scholarshipId: scholarshipRequest,
aidYear: aidYearRequest,
amount: amountRequest
}
}).success(function(response) {
if (!response.success) {
e.preventDefault();
alert(success);
} else {
e.preventDefault();
}
}).error(function() {
e.preventDefault();
alert("Error on Submission");
});
}
This function is called from here:
$("#SubmitTutorRequestFrm").submit(function(e) {
e.PreventDefault();
CheckForValidation(e);
});
I try to debug the code and put a breakpoint on Validate_ScholarshipRequest but that method never gets called. The method signature is:
public ActionResult Validate_ScholarshipRequest(string scholarshipId, string aidYear, string amount)
This is the start of my form:
#using (Html.BeginForm("SubmitScholarshipRequest", "Request", FormMethod.Post, new { id = "SubmitTutorRequestFrm" }))
Just to get this officially answered and "closed", this was caused by a syntax-error:
url: '#Url.Action("Validate_ScholarshipRequest", "RequestController")',
Controller should not be included in the controller name. The correct action would then be:
url: '#Url.Action("Validate_ScholarshipRequest", "Request")',
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
I am trying to call a controller via ajax without to much luck.
I have create this in my view
<input type="submit" id="preview-email" value="Preview Email" />
<script type="text/javascript">
$("#preview-email").click(function () {
var p = { "email": "1223" };
$.ajax({
url: '/BusinessController/PreviewEmail',
type: "POST",
data: p,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
});
</script>
My controller
[HttpPost]
public ActionResult PreviewEmail(string email)
{
// string d = ViewData["editor"].ToString();
string e = System.Web.HttpUtility.HtmlDecode(email);
EmailModel model = new EmailModel() { EmailBody = e };
return PartialView("_PreviewEmail", model);
}
Turning on fiddler is telling me that its a 500 error. What have I done wrong? I've placed a breakpoint on my controller however it doesnt get that far
Your URL should be:
'/Business/PreviewEmail'
instead of:
'/BusinessController/PreviewEmail'
However, the recommended practice for building URLs is to use your routes:
Url.Action("PreviewEmail", "Business")
BTW, you have another problem in your code. By setting "application/json" as your contentType, MVC will expect a JSON string. However, when you assign a JavaScript object to the data property of $.ajax(), jQuery will serialize the value to this:
email=1223
So you'll want to assign a string to the data property instead by doing this:
var p = '{ "email": "1223" }';
#Url.Action doesn't work inside the JS file. What if my call to Controller/Action is inside JS file?
For now I'm, retrieving the location.href and then replacing the Action name.
(This may not be a wise thing to do)