Play action not responding to json posted - java

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.

Related

How to retrieve json object in ajax onreadystatechange function

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);

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
}
}
}

if and else-if statements refuses to work in jquery's ajax function

I have a function that is called when a button is clicked, this function sends an ajax request using jquery. On success I have some logical if and else if statements. The web server can only send 2 types of text responses. It can either be "Success" or "Error". But when testing for these two conditions they seem to fail. I have added an else statement and an alert to tell me what the server is sending but just as I expected, it is either "Success" or "Error", the way I programmed my servlet in the server, it can only send "Success" or "Error" as response. Moreover my alert is spitting out "Success" or "Error" please I dont understand what is wrong here. please help.
function deleteRecord(productID, description)
{
var errorMessage = '<td class="red-left">There was an error. Please try again.</td>';
var successMessage = '<td class="green-left">Product '+productID+' ('+description+') has been deleted sucessfully.</td>';
var data = "productID="+productID+"&description="+description+"&deleteProduct=true";
$.ajax({
type: "GET",
url: "deleteInventoryRecord.mpcs",
data: data,
cache: false,
success: function(info)
{
if(info == 'Success')//This does not work
{
$(".green-left").replaceWith(successMessage);
$("#message-green").fadeIn("slow");
$("#product-"+productID).remove();
}
else if(info == 'Error')//This does not work
{
$(".red-left").replaceWith(errorMessage);
$("#message-red").fadeIn("slow");
}
else//This works always but I dont need it
{
alert(info); //It always says "Success" or "Error"
}
},
dataType: 'text'
});
}
Here is the servlet code that sends the response:
private void deleteProduct(HttpServletResponse response, String productID) throws IOException
{
try
{
response.setContentType("text/html");
InventoryDAO iDao = new InventoryDAO();
if(iDao.deleteProduct(productID) == true)
response.getWriter().println("Success");
else
throw new RuntimeException("Error");
}
catch(ClassNotFoundException | IOException | SQLException | RuntimeException xcp)
{
response.getWriter().println("Error");
}
}
Going to take a shot in the dark here, and say that the server is sending the response in UTF8 with a BOM, and this is causing your comparisons to fail.
To confirm, try alert(info.length). It should be 7 for "Success" or 5 for "Error". If it is not, then you probably have a BOM.
Another thing to check of course is that there is no whitespace in the response - again, the length check will help verify this.
You can fix this by encoding your server-side scripts as "UTF8 without BOM", sometimes referred to as "ANSI as UTF8" depending on your editor. Alternatively, change your if blocks to:
if( info.match(/Success$/)) ...
else if( info.match(/Error$/)) ...
Your deleteProduct method sets content type "text/html", but you are sending plain text. This is likely to confuse jQuery, as it tries to guess the type of info based on the content type header sent. Either use "text/plain", or even better "application/json", so you may sent more info to the client.

How I can do facebook batch fql in java

in facebook fql theres this code
https://developers.facebook.com/docs/reference/api/batch/
curl \
-F 'access_token=…' \
-F 'batch=[ \
{"method": "GET", "relative_url": "me"}, \
{"method": "GET", "relative_url": "me/friends?limit=50"} \
]'\
https://graph.facebook.com
it suppose to to be sent with json
but I really dont understand how to do this
any help ?
thanks
You can simple use the BatchFB api its very powerful and easy , you dont have to deal will all of these stuff and it use the fql
for example to get all your friends
Later<ArrayNode> friendsArrayList = this.Batcher.query("SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())");
for (JsonNode friend : friendsArrayList.get()) {
.......
}
and its batched
I believe your question is how to execute a batch request using Facebook Graph API. For this you have to issue a POST request to
"https://graph.facebook.com"
and the post data to be sent should be
"batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#accesstoken"
in your case [#accesstoken must be replaced with your access token value].
This request will return the details of the owner of the access token(normally the current logged in user) and a list of 50 facebook friends(contains id and name fields) of the user along with page headers(can be omitted).
I am not sure whether you meant java or Javascript. Please be specific on it.
I am a C# programmer basically. Will provide you a code to execute the above request in C# here.
WebRequest webRequest = WebRequest.Create("https://graph.facebook.com");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-UrlEncoded";
byte[] buffer = Encoding.UTF8.GetBytes("batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#ACCESSTOKEN");
webRequest.ContentLength = buffer.Length;
using (Stream stream = webRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
using (WebResponse webResponse = webRequest.GetResponse())
{
if (webResponse != null)
{
using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string data = streamReader.ReadToEnd();
}
}
}
}
Here the variable data will contain the result.
Salah, here is the example i use as reference, i am sorry though i do not remember where i found.
FB.api("/", "POST", {
access_token:"MY_APPLICATION_ACCESS_TOKEN",
batch:[
{
"method":"GET",
"name":"get-photos",
"omit_response_on_success": true,
"relative_url":"MY_ALBUM_ID/photos"
},
{
"method": "GET",
"depends_on":"get-photos",
"relative_url":"{result=get-photos:$.data[0].id}/likes"
}
]
}, function(response) {
if (!response || response.error) {
console.log(response.error_description);
} else {
/* Iterate through each Response */
for(var i=0,l=response.length; i<l; i++) {
/* If we have set 'omit_response_on_success' to true in the Request, the Response value will be null, so continue to the next iteration */
if(response[i] === null) continue;
/* Else we are expecting a Response Body Object in JSON, so decode this */
var responseBody = JSON.parse(response[i].body);
/* If the Response Body includes an Error Object, handle the Error */
if(responseBody.error) {
// do something useful here
console.log(responseBody.error.message);
}
/* Else handle the data Object */
else {
// do something useful here
console.log(responseBody.data);
}
}
}
});

Categories