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
}
}
}
Related
I'm very new to this, like really, really new.
I'm using Spring MVC (5.0) and am making an ajax call, as shown below.
This all works fine.
#RestController
public class AjaxController
{
#RequestMapping(value="/search/users", method=RequestMethod.GET)
public Person getUsers(#RequestParam("username") String username)
{
persons = personService.findPersonByUsername(username);
return persons.size() == 0 ? null : persons.get(0);
}
}
The method gets the person from the database and returns it.
According to the Spring Restful guide,
"The XXX object must be converted to JSON.Thanks to Spring’s HTTP message converter support, you don’t need to do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the XXX instance to JSON."
So, Spring is automatically generating the JSON which will be returned to the client. The problem is, I get an error message in my client javascript:
SyntaxError: JSON.parse: unterminated string literal at line 1 column 103911 of the JSON data
My client javascript is equally simple, consisting of only:
function ajax_get_users(input_box)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "users?username=" + username, true); // url of server-side ajax script, specify synchronous ajax call
// get asynchronous response
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var person = JSON.parse(this.responseText); // this is where the unterminated String error occurs
}
};
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // set http header
xhttp.send(); // send the ajax request to the web server
}
Since Spring is constructing the JSON, how do I even fix the problem?
Hi I am currently developing a simple converter for Fahrenheit and celsius using Restful web services.
Currently I have values printing out in json using the following code written in java
//JSON Converted Values
//Fahrenheit to Celsius converter
#GET
#Path("/fjson/{number1}")
public String FJson(#PathParam("number1") double num1){
//String output = Double.toString((1.8)*num1 - 32);
Gson gson = new Gson();
String output = gson.toJson(new Result (Double.toString(5.0/9.0*(num1 - 32))));
//Response response = Response.status(200).entity(output).build();
return output;
}
//Celsius to Fahrenheit converter
#GET
#Path("/cjson/{number1}")
public String CJson(#PathParam("number1") double num1){
//String output = Double.toString((1.8)*num1 - 32);
Gson gson = new Gson();
String output = gson.toJson(new Result (Double.toString((1.8)*num1 + 32)));
//Response response = Response.status(200).entity(output).build();
return output;
}
But I want to be able to call these methods say for example a simple page with a box and a button where the user enters the value and it converters and output in a simple html value say a <p>
Heres what the current output looks like
Any help would be great
The simplest solution I can think of, to consume JSON responses as HTML, is to use an ajax call with jQuery. If you're not to familiar with jQuery (or Javascript) I suggest you do some reading. A primer for doing so (even though you're not using Spring) can be found here.
Your solution might be a file with example html like below:
<input id="input" type="text">
<input id="change" type="button" value="Click me">
<p id="output"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var input = $("#input");
var output = $("#output");
$("#change").on('click', function() {
$.ajax({
'url' : 'http://localhost:8080/api/convertor/cjson/' + input.val(),
'type' : 'GET',
'dataType' : 'json',
'success' : function(data) {
output.html(data.converted);
}
});
});
</script>
Minor suggestion: serve the html page up with your server, incase there are CORS issues.
If you are creating REST endpoints that are to be consumed by a client (such as a javascript client like above), then I'd suggest also do some more reading, as you'll quickly see that the above code doesn't help you built the client out.
Like above, there is a demo in jsbin(http://jsbin.com/befifu/14/edit?html,css,js,output). Which use a static json file to simulate the rest api.
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);
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!
I'm new to play and I am trying to post form data to my Play Action using JQuery. However, I'm getting "expected json" response from Action. I check the HTTP Headers to ensure that the data is being sent and it is so, where am I going wrong and how can I fix it.(Is there a better approach to this)
Script:
$(document).ready (function (){
$("form").submit (function (e) {
e.preventDefault();
$.post("/save",$(this).serialize(),function (data){
alert(data);
});
});
});
Action
public static Result save()
{
JsonNode json = request().body().asJson();
if (json == null)
return ok("expected json");
else
{
String value = json.findPath("video").getTextValue();
if (value == null)
return ok("did not find");
else
return ok(value) ;
}
}
routes
POST /save controllers.Application.save()
Both: Julien Lafont and dfsq are right, first: you are not serializing your form to JSON, second, as Julien stated, you don't need to... Using your current JS you can just use DynamicForm in your save action:
public static Result save() {
DynamicForm df = form().bindFromRequest();
String value = df.get("video");
if (value == null || value.trim().equals(""))
return badRequest("Video param was not sent");
// do something with the value
return ok(value);
}
BTW, don't use ok() for returning responses for wrong requests. You have many options: badRequest(), notFound(), TODO, and wild bunch of other Results, even raw: status(int), so you can read the status in jQuery without passing any additional reasons of fail.
If you really, really need to serialize form to JSON for any reason, let me know, I'll send you a sample.