how can i retrieve JSON object in servlet upon success - java

I am using jQuery/AJAX call to pass control to servlet and upon success sending control to another servlet. Not sure how can I retrieve JSON object set by first sevlet to second. Here is my pseudo code.
orders.jsp
---------------
// display orders
// on click calls following ajax
$.ajax({
url : "processorder",
type : "POST",
dataType : "text",
data : formData,
success : function(data, textStatus, jqXHR) {
var successUrl = "checkout"; //upon success pass the control to checkout.java
window.location.href = successUrl;
return false;
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Oops ! Error occurred !");
}
});// End of ajax
processorder.java (servlet)
-------------------------------
Processes data
Set some session variables
List<OrderDetails> newod = new ArrayList<OrderDetails>();
Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
JsonElement orderDetailElement = null;
//update orderDetailElement
orderDetailElement = gson.toJsonTree(newod);
jsonObject.add("OrderDetails", orderDetailElement);
request.setAttribute("OrderDetails", newod); //set the session with orderdetails
out.print(jsonObject.toString()); // write object to json
checkout.java (servlet)
----------------------------
**How can I access JSON object which I am sending from processorder?**
any idea?

You need to make an ajax call inside success function of your first ajax call.
Something like
$.ajax({
url : "processorder",
type : "POST",
dataType : "text",
data : formData,
success : function(response) {
$.ajax({
url : "checkout",
type : "POST",
dataType : "text",
data : response,
success : function(response) {
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Error ");
}
});
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Oops ! Error occurred !");
}
});

Related

Ajax response arrives empty from spring controller, even if it succeeded

I received empty data from spring controller, even if it returned data the ajax success function received it empty. I tried to return string directly from controller like this:
#ResponseBody
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(#RequestParam("posImsi") String posImsi,#RequestParam("posMsisdn") String posMsisdn){
return "success";
}
and the ajax is:
$.ajax({
url : "test",
type : "POST",
data : formData,
beforeSend : function(){
$("#overlay").show();
},
success : function(ajaxResult){
console.log(ajaxResult);
},
complete : function(status) {
},
error : function(jqXHR, status, errorThrown) {
alert(jqXHR);
alert(status);
alert(errorThrown);
}
});
The problem is solved by using the XMLHttpRequest object to do ajax request, I really don't know what is the difference but here is what I used:
var x = new XMLHttpRequest();
x.open("POST","test",true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.send(formData);
x.onload = function () {
console.log(this.responseText);
};
for more information about XMLHttpRequest object: http://www.w3schools.com/xml/dom_http.asp

Need to get the response and to have change in ajax jquery GUI

I have the restful webservices call from the Jquery ajax and getting the response in json object.
Jquery HTML:
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
},
error: function (error, data) {
console.log(error);
}
});
}
});
And writing the response object for the restful webservices in java
#POST
#Path("api/{subsystem}")
#Produces("application/json")
public Response changeStatus(#PathParam("subsystem") String subsystem,
/*#FormParam("result")*/ String result) {
}
I got the response below and which is correct
changeStatus:88 - Reponse OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
Depending upon the reponse need to update the status whether the value is on/off in the label tag.
str = ' Status : ' + '' + onoffStat + '';
How can I achieve this in ajax and want to have the refreshing the div tag for every 2 seconds.
Please help me.
You will have to use Javascript polling. Try out something like this:
function ajaxPoll(){
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
tag.str = 'Status : ' + '' + ResData.status + '';
},
error: function (error, data) {
console.log(error);
}
});
}
});
}
setInterval(ajaxPoll, 2000);
Hope you sort it out :)

Getting JavaScript JSON string to populate DataTable

I have a java function that gets a JSON string of data from a Servlet in Java. I am trying to use that data to populate a datatable (http://www.datatables.net/examples/data_sources/ajax.html)
This is the way that the DataTables website instructs users to populate datatables:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
And this is the javascript method that calls the doPost method in my servlet to generate and return the JSON:
<script>
$(document).ready(function() { // When the HTML DOM is ready loading, then execute the following function...
//$('#somebutton').click(function() { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
async : false,
success : function() {
console.log("ok");
alert("ok");
}
}).responseText;
console.log(bodyContent);
});
</script>
How can I get the JSON string in var bodyContent to populate the datatable?
First off, you're not really doing AJAX; when you do:
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
async : false,
success : function() {
console.log("ok");
alert("ok");
}).responseText;
You set async: false ... but AJAX stands for Asynchonous Javascript and XML. With an AJAX approach the following happens:
You start the request by doing $.ajax
The server takes however long to respond; the user's browser is not locked up during this time
When the server responds the success callback you defined gets called
With your approach
You start the request by doing $.ajax
The user's browser is locked up while waiting for a response
When the server responds your code (after the $.ajax call) is invoked.
To make your code actual AJAX do this instead:
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
success : function(responseText) {
bodyContent = responseText
}
});
Of course, once the response comes back you also need to build your Data Table, so what you really want is:
success : function(responseText) {
$('#example').dataTable( {
"data": responseText
});
}
(Or something to that effect; I forget DataTable's exact syntax.)
Refer to jQuery.ajax docs. The data returned from server in first argument of success callback. Also note that all manipulations with this data whould be inside this callback. I guess you should additionally check status argument:
$(document).ready(function() {
var bodyContent = null;
$.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
success : function(data, status) {
console.log(data);
$('#example').dataTable( {
"data": $.parseJSON(data),
"columns": [
{ "title": "Engine" },
{ "title": "Browser" },
{ "title": "Platform" },
]
});
});
});
});
UPDATE To populate data server should respond with JSON encoded array of data and you should parse it and pass to dataTable as it noted here.

Handle JSON Array posted from Ajax in Struts 1.3

I build the JSON Object like this:
var key = //some calculated key
var key = //some calculated value
var list = {item: []};
list.item.push({
"key" : key,
"value" : value
});
Then I send the array like this:
sendData = function() {
$.ajax({
url :'<html:rewrite action="/sendData"/>',
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data : {"list":list.item},
success:function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
How can I retrieve in my action the JSONArray/JSONObject and handle it?
I've tried this:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String list = request.getParameter("list"); //null, I supposed to find a string formatted like json
return null;
}
Even GSON library is allowed!
You will get significant improvement if you convert your object to string when sending it as parameter.
data : {list: JSON.stringify(list.item)}

get value from servlet using ajax

I want to fetch object from servlet.
I try below code but I get "[object Object]" . I want "Description" value.
I got out in browser when I run http://www.host.com/f/ServletToJSP1/*
o/p {"Description":"Nutanix provides disruptive datacenter infrastructure solutions that are hyper-efficient, massively scalable and elegantly simple."}
in console log :Uncaught ReferenceError: google is not defined
How can I do that ?
jsp code
$.ajax({
url : 'ServletToJSP1',
type : 'GET',
dataType : 'json',
success : function(response) {
//response = $.parseJSON(response);
alert(response);
},
error : function(error) {
//error handling....
alert(error);
}
});
servlet code
JSONObject objTw = new JSONObject();
objTw.put("Description", "Nutanix provides disruptive datacenter infrastructure solutions that are hyper-efficient, massively scalable and elegantly simple.");
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
out.println(objTw);
Access the description property on the response object.
$.ajax({
url : 'ServletToJSP1',
type : 'GET',
dataType : 'json',
success : function(response) {
//response = $.parseJSON(response);
alert(response.Description);
},
error : function(error) {
//error handling....
alert(error);
}
});
Are you developing in Chrome?
You can open the dev tools with CTRL+SHIFT+I then open the Console.
Instead of alert(respone) try console.log(response) to have a deeper look into the variable.
Try
success : function(response) {
alert(response[0].Description);
},
and in your servlet code try to add out.flush();

Categories

Resources