How to retrieve json object in ajax onreadystatechange function - java

I have servlet calling in ajax call. It send json object in response. Now I have receive this json in jsp and place data in table format. Can someone help me in this. Here is my code,
I am calling servlet as,
xmlHttpReqRM.open('POST', "RTMobitor?rtype=rmonitor", true);
my servlet, Here vehicleList is a list object
latlng.setLng(resultSet.getString("lng"));
latlng.setStatus(resultSet.getString("status"));
latlng.setRdate(resultSet.getString("rdate"));
latlng.setRtime(resultSet.getString("rtime"));
vehicleList.add(latlng);
System.out.println(vehicleList);
String json = new Gson().toJson(vehicleList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Previously I was sending response as a text, it was easy but now I changed to json. I am not getting how to receive,
xmlHttpReqRM.onreadystatechange = function() {
if (xmlHttpReqRM.readyState == 4) {
if (xmlHttpReqRM.status == 200) {
var responceeString = xmlHttpReqRM.responseText; // How to replace this ajax code for json
document.getElementById("flexme1").innerHTML = (responceeString);
} else {
alert('ERR OR: AJAX request status = ' + xmlHttpReqRM.status);
}
How can I replace this ajax code for json. Can anyone help me in this please.

var jsonObject = JSON.parse(responceeString);

Related

AngularJS $http get return null status 0

I'm trying to create $http get request to fetch some json data generated by my web service, but it returns null error. However, the $http request works fine when I use this sample url instead (it returns json string too)
This is my angular code :
angular.module('ionicApp', ['ionic'])
.controller('ListCtrl', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get("http://localhost:8080/InventoryCtrl_Service/webresources/IVC_Service/GetUserList")
.then(function(response) {
console.log("success ");
},
function(response) {
console.log("Error : " + response.data + " Status : " + response.status);
}
});
This is my web service code :
#GET
#Path("/GetUserList")
#Produces("application/json")
public Response GetUserList() throws SQLException {
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject outerObject = new JSONObject();
JSONArray arr = new JSONArray();
obj1.put("Name", "Sara");
obj2.put("Name","David");
arr.add(obj1);
arr.add(obj2);
outerObject.put("records", arr);
return Response.status(200).entity(outerObject.toString()).build();
}
When I run the above code, it returns json string like this :
{"records":[{"Name":"Sara"},{"Name":"David"}]}
The console log returns this :
Error : null Status : 0
What is the meaning of the null error? Or is there anything wrong with how I return the json string?
Try using JSON_STRINGIFY, this will convert your incoming data into String format.
console.log(JSON_STRINGIFY(response.data));
TO verify what data your web service is returning, you can always check it by hitting your web service via postman.
I managed to solve this by adding CORS (Access-Control-Allow-Origin) to the response header, based on another SO answer. There's no problem with my angular code, it's just that I need to modify my web service code to enable the CORS. So I just modified the part where it returns data to become like this :
return Response.status(200).entity(outerObject.toString()).header("Access-Control-Allow-Origin", "*").build();

Parse the json string : receiving from a java code

I need to send the string s or json to ajax .done function. Here is the servlet code that has an object list to be sent for an ajax request.
Gson gson = new Gson();
Tester t = new Tester(10,"s");
Tester t2 = new Tester(20,"g");
LinkedList<Tester> list = new LinkedList<Tester>();
list.add(t); list.add(t2);
String s = gson.toJson(list);
I need to send the json to ajax. How could I do this? I could do :
out.println(s);
But how would I then parse the string? I need to appropriately put the json data received into the html table.
The current json output from out.println(s) is [{"x":10,"y":"s"},{"x":20,"y":"g"}]
js function that will receive json :
function getFeFeeds() {
$.ajax( {
url : '',
dataType : 'json',
type : 'GET'
}).done(function(message) {
}).fail(function(message) {
});
}}
You need to iterate over the received json and do your processing -
$.each(message, function(index, row) {
console.log(row[0].x);
console.log(row[0].y);
});
Also I would suggest set encoding so that you don't have any encoding related issues -
response.setCharacterEncoding("UTF-8");

Java : How to handle POST request without form?

I'm sending a http post request from javascript, with some json data.
Javascript
var data = {text : "I neeed to store this string in database"}
var xhr= new XMLHttpRequest();
xhr.open("POST","http://localhost:9000/postJson" , true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(data);
xhr.setRequestHeader("Connection", "close");
//Also, I've tried a jquery POST
//$.post('postJson', {'data=' : JSON.stringify(data)});
//But this doesn't make a request at all. What am I messing up here?
Route
POST /postJson controllers.Application.postJson()
Controller
public static Result postJson(){
//What should I write here to get the data
//I've tried the below but values is showing null
RequestBody rb=request().body();
final Map<String,String[]> values=rb.asFormUrlEncoded();
}
What is the way to parse the POST request body?
Much thanks!
Retreive the request body directly as JSON... no need to complicate your life.
public static Result postJson() {
JsonNode rb = request().body().asJson();
//manipulate the result
String textForDBInsertion = rb.get("text").asText(); //retreives the value for the text key as String
Logger.debug("text for insertion: " + textForDBInsertion
+ "JSON from request: " + rb);
return ok(rb);
}
Also, I recommend you use the AdvancedRestClient Chrome plugin for testing. This way you can eliminate from the equation client-side code errors.
Cheers!

Request objects with ajax and process them

I'm trying to learn Ajax partial-page rendering.
So far, I managed to request a String and write it in the page. Now I'm trying to request an object, and I'm stuck.
Lets say I have this in my Ajax controller
MyClass obj = new MyClass();
obj.setA("Content of A");
obj.setB("Content of B");
obj.setC("Content of C");
PrintWriter out = response.getWriter();
What would be a good way of sending instance to an ajax request?
My Ajax script looks like this:
function getData(){
// .. //
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById("result").style.display='block';
// How to handle xmlHttp response ?
}
}
}
xmlHttp.open("GET", "/index2", true);
xmlHttp.send(null);
}
And in my html I should get this:
<div id="result" style="display:none">
<a href="obj.A">
obj.B
</a>
</div>
I know you cannot request a MyClass instance, but I heard you can request xml or table, how could I turn my MyClass instance in a xml or table format, and how could I process it in my ajax response handler? Is there a better way then my xml ideea?
When you export object, I recommend using json format (xml is also a possibility but is much harder to process using javascript)
You can see this topic to learn how to convert Java object to JSON : convert java object to json and vice versa
Property responseText contains response
xmlHttp.onreadystatechange = function ()
{
if (xmlHttp.readyState == 4)
{
if (xmlHttp.status == 200)
{
document.getElementById("result").style.display='block';
var response = JSON.parse(xmlHttp.responseText);
// precess response
}
}
}

Retrieve JSON object after jQuery get finish

I'm trying to retrieve JSON object using jQuery get, and the Object I retrieve I want to embed in innerHTML. The following code is how i construct my JSON
getListOfActivity.jsp
<%
String urusStr = request.getParameter("ukid");
int urusId = Integer.parseInt(urusStr);
lkpPdkCommon[] activity = getListOfActivity(urusId);
if(activity!=null){
out.println("{PartList:");
out.println("[");
for(int x=0;x<2;x++){// the lkpPdkCommon[] return from getListOfActivity(urusId) huge so I limit the array to 2
out.println("{");
out.println("ActivityID:\""+activity[x].getID()+"\",Description:\""+activity[x].getDescription()+"\"");
out.println("}");
if((x+1)!=2){
out.println(",");
}
}
out.println("]");
out.println("}");
response.setContentType("application/json");
%>
and below code is my jQuery/jscript
var ukid = document.getElementById("ukid").value
var aktivityId = row.insertCell(1);
var description = row.insertCell(2);
var JSONObject;
var $ac = jQuery.noConflict();
$ac.get("../../getListOfActivity.jsp",{ukid:ukid}, function(data){
JSONObject = data
//for testing purposes I do not iterate through the JSON Object
aktivityId.innerHTML = JSONObject.PartList[0].ActivityID
description.innerHTML = JSONObject.PartList[0].Description
});
The following code didn't return any error, but it seems doesn't work. This is the JSON Object I check using firebug
Have you tried Jquery getJSON.
I think this would help you.
http://api.jquery.com/jQuery.getJSON/
The problem solved after I modified the following line in jsp
out.println("{PartList:");
to
out.println("{\"PartList\":");
and
out.println("ActivityID:\""+activity[x].getID()+
"\",Description:\""+activity[x].getDescription()+"\"");
to
out.println("\"ActivityID\":\""+activity[x].getID()+
"\",\"Description\":\""+activity[x].getDescription()+"\"");
The original JSON object send by response header before I do the modification are like below:
{PartList:
[
{ActivityID:"8638",Description:"GERMS"},
{ActivityID:"8639",Description:"GOVERNMENT CERTIFY PROGRAMMES"}
]
}
and after the modification
{"PartList":
[
{"ActivityID":"8638","Description":"GERMS"},
{"ActivityID":"8639","Description":"GOVERNMENT CERTIFY PROGRAMMES"}
]
}

Categories