ModelView, Ajax and Json return - ajax

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.

Related

Pass a form and an array through a single ajax

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!

Receiving response as JSON in ajax call in jsp

I have a jsp page that sends response as a json. The page is requested through AJAX call. But the response went into Ajax error part instead of success part.
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers
The following is my jsp page Script:
$("#Student").delegate("select[id='year.id']", "change", function () {
//alert("hi");
var id = $(this).attr('id');
var value=$("select[id='year.id']").val();
//alert(id);
//alert(value);
//console.log($(id).val());
$("select[id='classs.id']").empty();
$("select[id='classs.id']").append('<option value="">Select Class</option>');
$("select[id='section.id']").empty();
$("select[id='section.id']").append('<option value="">Select Section</option>');
$.ajax({
type: 'GET',
url: 'getStandard',
contentType: "application/json;charset=utf-8",
datatype: "Json",
data: { Year: value },
success : function(datas) {
$.each(datas, function (i, data) {
$("select[id='classs.id']").append('<option value="' + data.id + '">' + data.name + '</option>');
});
}
});
return false;
});
This Is my server side code where I am getting the response as Student object :
Controller :
#RequestMapping(value = "/getStudentName", method = RequestMethod.GET)
public #ResponseBody String getStudentName(#RequestParam("Year") String idYear, #RequestParam("Classs") String idClass, #RequestParam("Section") String idSection) throws JsonProcessingException
{
List<Student> student = userService.getStudentName(idYear,idClass,idSection);
return student ;
}
I am new to ajax using via Spring
#RequestParam is a parameter in the uri (http://uri?year=2018). If what you want is JSON then you should use #RequestBody instead

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(.....) {
// ...
}

how to send an object from spring controller to jsp through 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

call controller using ajax failing to find controller

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)

Resources