respond to AJAX request with JSON object? - java

I am doing a toy program that asks user to input "username" and "fullname" on an html form, the form will be submitted by AJAX to the following method in Spark framework (see here for Spark:
post("/admin/user/signup", "application/json", (request, response) -> {
String username = request.queryParams("username");
String fullname = request.queryParams("fullname");
System.out.println("username is: " + username +", full name is: " + fullname);
Map<String, Object> registerResults = new HashMap<String, Object>();
registerResults.put("success", "successfully registered " + username);
return new MyMessage("successful registration!");
}, new JsonTransformer());
And the following is my AJAX code that supposedly submits and receives the response from the above post() method:
<script>
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize(); /* capture the form data*/
$.getJSON('/admin/user/signup', formData, registerResults);
// $.post('/admin/user/signup', formData, registerResults); /* get JSON back from the post method */
});
function registerResults(data) {
$('#registerForm').fadeOut();
$('.starter-template').html(data.message);
} // end of registerResults
}); // end of ready
</script>
However, the AJAX code cannot receive the JSON object, instead the JSON object is simply printed on the web page /admin/user/signup:
{"message":"successful registration!"}
So I am asking for help how to return the JSON object to AJAX request in Spark? thanks

You do realize that you are submitting the form. So instead of the supposed AJAX call the form is being submitted and hence the resulting page ...
So you should stop the form submit propagation by simply adding
event.preventDefault();
OR return false; at the end of the submit handler.
in the form submit handler.
<script>
$(document).ready(function() {
$('#registerForm').submit(function(event) {
event.preventDefault();
var formData = $('#registerForm').serialize(); /* capture the form data*/
$.getJSON('/admin/user/signup', formData, registerResults);
// $.post('/admin/user/signup', formData, registerResults); /* get JSON back from the post method */
});
function registerResults(data) {
$('#registerForm').fadeOut();
$('.starter-template').html(data.message);
} // end of registerResults
}); // end of ready
</script>

Instead of return new MyMessage("successful registration!");
Just pass like this return new MyMessage(registerResults);
now,you are not returning this registerResults map value.
I hope you are using play framework.then it should work
And one more thing,you should deny the form from submitting. so, use
$('#registerForm').submit(function(e) {
e.preventDefault();
// do your stuff here
});

You can not treat json as HTML by using html() function, you need to parse it by parseJson() function from jQuery: http://api.jquery.com/jquery.parsejson/
var obj = jQuery.parseJSON(data);
$('.starter-template').html(obj.message);

Related

Java Rest call with jquery and ajax

I am making a ajax Rest call within jquery and it is supposed to return me a list of beans, which I want to show in the jsp. I am able to make the Rest call but I can't get how to get the result in the ajax call and show it in page.
jsp page with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$('#abcForm').submit(function(){
var v = $('#abc').val();
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/RestTest/rest/hello/"+v,
});
});
});
</script>
java code
#Path("hello")
public class RestController {
#GET
#Path("{param}")
public Response getMsg(#PathParam("param") String msg) {
String output = "Hello : " + msg;
return Response.status(200).entity(output).build();
}
}
So actually there will be a rest call from the java class and it will return a list which needs to be shown in the jsp page as ajax call. This is where I am stuck.
Help needed.
Thanks
You have a success callback that will be called when the request finishes as successful and will receive the response as the first parameter:
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/RestTest/rest/hello/"+v,
success: function(data) {
//do something with data.
}
});

How to correctly handle this AJAX request that send an array to a Spring MVC controller method? Why it can't work?

I am pretty new in Spring MVC and I have the following problem trying to handle an AJAX request that send an array of int to a controller method.
So I have the following situation. I have this JQuery function:
// It is global and it is initiazilized by another function:
var checkedRowList = new Array();
// SOME OTHER CODE THAT INIZIALIZED THE checkedRowList array here
...............................................
...............................................
...............................................
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: {'checkedRowList' : checkedRowList},
url: "validaProgetti"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
So the checkedRowList is correctly initizialized (I checked it) and I use the ajax() function to send it toward the validaProgetti resource using a POST request.
Then into a controller class I have this method that have to handle the previous request:
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public String validaProgetti(#RequestParam List<Integer> checkedRowList, Model model, HttpServletRequest request) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
As you can see it handle HTTP Post request toward the validaProgetti resource. And Inside it I have specify the RequestParam List checkedRowList to retry the array passed by the AJAX request.
But it don't work because when the AJAX request is performed it don't enter into the validaProgetti() method and it shown the alert("SUCCESS"); popup.
Why? What am I missing? How can I fix this situation?
as I see you missed two things.
The first one is that in the Spring Web MVC controller. You don't pass a RequestParam but RequestBody.
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
The second one is related with your Ajax request. You should send javascript array formatted as JSON. This is done via the function JSON.stringify(), which converts js value into json.
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: JSON.stringify(checkedRowList),
url: "validaProgetti",
contentType:"application/json"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
Also you may change the request mapping when defining in java code. Since it is a relative path, it would be confusing in some cases.
#RequestMapping(value = "/validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}

Returning Hashmap From controller to JSP in Springmvc

I have two dropdownlists in Jsp One for state and other for country. As soon as i select country the statelist should be populated automatically with respective lists. But i am getting whole jsp page as response in ajax call.
My ajax Program:
$("select#country").change(function() {
var val=$("#country").val();
alert(val);
$.ajax({
url : 'getstates',
method : 'get',
contentType: 'application/json',
data :{
country : val
},
success: function (data) {
alert("Success Response"+ data);
},
error :function()
{
alert("error");
}
});
My controller program
#RequestMapping(value = "/getstates", method = RequestMethod.GET)
public ModelAndView showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, Model model) {
HashMap<String,String> stateMap = new HashMap<String,String>();
//put your logic to add state on basis of country
if (country.equals("UnitedStates")) {
stateMap.put("Al","Alaska");
stateMap.put("Tl","Texas");
} else if (country.equals("UnitedKingdom")) {
stateMap.put("Be","Bedfordshire");
stateMap.put("Ber","Berkshire");
} else if (country.equals("India")) {
stateMap.put("Mh","Maharashtra");
stateMap.put("WB","West Bengal");
stateMap.put("KR","Karnataka");
stateMap.put("AP","Andhra Pradesh");
stateMap.put("TN","Tamil Nadu");
}
return new ModelAndView("LoginForm","state" ,stateMap);
}
I am using spring form. I need to get only Staemap as respone but i am getting whole jsp page as response.
I need to get only Staemap as respone but i am getting whole jsp page
as response.
Because you are returning the ModelAndView object with the view here,
return new ModelAndView("LoginForm","state" ,stateMap);
If you need to return the respone alone from the controller method.However you cant print the HashMap directly in the ajax response on your jsp. IMHO you can convert it to JSONArray
JSONArray jarray = JSONArray.fromObject(statemap);
Read ,
send array from controller to a view using JSON in MVC
Sending JSON response from spring controller
loop through json array jquery
#RequestMapping(value="LoadBaselineVersions")
#ResponseBody
public Map<Integer,String> loadBaseNames(#RequestParam(value="projectname") String name,HttpSession session){
return basenameService.getBaselineversions(name);
}
$("#projectname").bind(
'blur',
function() {
$.ajax({
type : 'post',
url : 'LoadBaselineVersions?projectname='
+ $("#projectname").val(),
dataType : 'json',
success : function(data) {
$("#baseversion").empty();
$.each(data, function(val, text) {
$("#baseversion").append(
$('<option></option>').val(text).html(
text));
});
}
});
});

Want the navigating page on the same page

my ajax some how looks like this :
function getXMLHttpRequest() {
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "http://abc.com:8080/someservletServlet/", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
}
function getReadyStateHandler(xmlHttpRequest) {
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("xml").value = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
} but somehow the servlet is not bringing the response it should bring. can you help. what could be the possible error.
Ajax is the way to go.Because if you submit the request, page will refresh whether its same page or different.
If you still want to achieve it using without using ajax and refresh of page is fine with you then see if you have this kind of code in your servlet which is causing to forward it to some other page
String nextJSP = "nextPage.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
If you need to load some data from some other URL you'll need to send an AJAX request (explain where to get data from) and handle the AJAX response (explain what to do with the fetched data). To provide for a browser-compatible solution you'd better use some well-known JS library. For example, you could use jQuery in which case your script could look like:
$.ajax({
url: "servletURL",//servlet URL to post data to
type: "POST",//request type, can be GET
cache: false,//do not cache returned data
data: {id : idOfData},//data to be sent to the server
dataType: "xml"//type of data returned
}).done(function(data) {
//do something with XML data returned from server
});
With this approach you need to call the above JS code, probably wrapped in a JS function, on some JS event, i.e. click, and handle response data, for example, by appending its contents to your text area.

How to pass a value of a variable from a java class to the jsp page

I have 2 files named Admin.java and index.jsp.
In Admin.java through a function I retrieve the value of the varible named res. This variable needs to be passed to a JSP page.
The Admin.java is in C:\Users\praveen\workspace\SemanticWeb\src\controller whereas the index.jsp is in C:\Users\praveen\workspace\SemanticWeb\WebContent.
The code of Admin.java is:
public Admin()
{
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
if (action.equals("login"))
{
String userName="";
String password="";
userName = request.getParameter("username");
password = request.getParameter("password");
response.setCharacterEncoding("UTF-8");
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);
request.setAttribute("rest", res);
return;
}
The code of index.jsp is
function login(user, pass)
{
$.ajax({
type:"GET",
url: "Admin?action=login",
dataType: "text",
data: { username: user, password: pass },
success: function(response){
}
within the
function(response)
{
......
}
I need to access the value of res passed by Admin.java. I am not able to get any proper help for my code on the Internet. Please can someone help me with this.
From your code,
request.setAttribute("rest", res);
You shouldn't set it as request attribute. Setting request attributes is only useful if you're forwarding to a JSP file. You need to write it straight to the response yourself. Replace the line by
response.getWriter().write(res);
This way it'll end up in the response body and be available as variable response in your JS function.
See also:
How to update current page by Servlet/Ajax?
Seems like you're doing AJAX, so I'd say your response would need to be encoded in an AJAX-compatible way (JSON, XML, ...).
If you do AJAX-encoding, your function might look like this:
function(response)
{
var toplevel = response.<your_top_level_element>;
}
Edit:
We're using JSON Simple for JSON encoding.
Our Java backend then looks like this (simplified version without error checking):
public String execute()
{
JSONObject jsonResult = new JSONObject();
jsonResult.put( "result", "ok");
return jsonResult.toJSONString();
}
And in the Javascript function:
function(response)
{
var result = response.result; //now yields "ok"
}
If this is an ajax request, you can forward the request into another jsp page rather than return. With this
getServletContext().getRequestDispatcher("/ajax.jsp").forward(request, response);
create the jsp page(ajax.jsp) on your webcontent and add this sample code.
<p>${rest}</p>
<!-- Note: You can actually design your html here.
You can also format this as an xml file and let your js do the work.
//-->
Another way is replace your System.out.println with this
PrintWriter out = response.getWriter();
out.print("The value of res been passed is "+res);
but I guess this is a bad practice. See example here.

Categories