I'm getting a null JsonNode object in the following code. There's something wrong with the client javascript. If I run a curl command with a POST request, I get the correct response. If I run the same in the below mentioned Javascript - I get a null for the JsonNode object. Here's the code
Application.java
package controllers;
import org.codehaus.jackson.JsonNode;
import play.Routes;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
public class Application extends Controller {
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result receiveData() {
response().setContentType("application/json");
JsonNode json = request().body().asJson();
if(json == null) {
return badRequest("Expecting Json data");
} else {
String name = json.findPath("name").getTextValue();
if(name == null) {
return badRequest("Missing parameter [name]");
} else {
return ok("Hello " + name);
}
}
}
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("jsRoutes",
// Routes
controllers.routes.javascript.Application.receiveData()
)
);
}
}
Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
POST /receiveData controllers.Application.receiveData()
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
main.scala.html
#(title: String)(content: Html)
#import helper._
#import controllers.routes.javascript._
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/bootstrap.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script type="text/javascript" src="#routes.Application.javascriptRoutes"></script>
<script src="#routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/bootstrap.js")" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/message.js")" type="text/javascript"></script>
</head>
<body>
<div class="container">
<div class = "row">
<div class = "span12">
<input type = "text" id = "inputValue" value="getData"></input>
<button class = "approveButton btn btn-primary">Approve </button>
</div>
</div>
</div>
</body>
</html>
message.js
$(document).ready(function(){
$('.approveButton'). click(function(){
var value = $('#inputValue').val();
var jsonToSend = {};
jsonToSend.name = value;
var outputData = JSON.stringify(jsonToSend);
jsRoutes.controllers.Application.receiveData().ajax({
data:outputData,
contentType:'application/json',
success: function(data) {
console.log(data);
},
error: function() {
alert("Error!");
}
});
});
});
Here's the output of the curl command:
curl --header "Content-type:application/json" --request POST --data '{"name":"abx"}' http://localhost:9000/receiveData
Hello abx
Can someone please help in identifying whats wrong in the javascript file.
The expected result of the ajax call is a json object. In this case if you want to response with a plain text add dataType: 'text' to the request:
jsRoutes.controllers.Application.receiveData().ajax({
data:outputData,
dataType: 'text',
contentType:'application/json',
success: function(data) {
console.log(data);
},
error: function() {
alert("Error!");
}
});
Maybe a stupid question but what does you make think, that ajax call will be POST instead of GET ? Have you tried replacing POST by GET ?
Related
I'm trying to use Microsoft Azure Face API in Javascript to verify two faces. I follow their sample codes and found one javascript API. In the below sample code how can I pass the two images that I want to verify in the body section of this API? Can someone give me an example pls?
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
};
$.ajax({
url:
"https://westus.api.cognitive.microsoft.com/face/v1.0/verify?"
+ $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","
{subscription key}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Below sample works for me.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
faceapi();
})
function faceapi(){
var SendInfo= { faceId: '43a4de00-e750-4bb8-8379-de3b33c9c0a6',personId:'2c0f2289-68cc-4cf6-ab12-9c0eec6bf3c7',largePersonGroupId:'112233'};
$.ajax({
type: 'POST',
url: 'https://yoursourcename.cognitiveservices.azure.com/face/v1.0/verify',
dataType: 'json',
data: JSON.stringify(SendInfo),
beforeSend: function(request) {
request.setRequestHeader("Content-Type", 'application/json');
request.setRequestHeader("Ocp-Apim-Subscription-Key", 'yourkey');
},
success: function(res){
console.log(res)
}
});
}
</script>
</head>
<body>
</body>
</html>
You can easily use our face verification api which is available for free in rapidapi
I am trying adapt my app to use angular, but currently it seems that spring cannot see/communicate with angular. Here is what i have :
Controller.java:
#Controller
public class IndexController {
#RequestMapping(value = "/login", method = RequestMethod.GET, produces = {"application/json"})
public #ResponseBody Map<String, Object> getIndexPage() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello Worl123321");
return model;
}
}
index.html:
<!doctype html>
<html>
<head>
<title>Title</title>
<!--<link href="css/angular-bootstrap.css" rel="stylesheet">
<link rel="stylesheet" href="css/app.css"/>-->
<style type="text/css">
[ng\:cloak],
[ng-cloak],
.ng-cloak {
display: none !important;
}
</style>
<script src="js/angular-bootstrap.js" type="text/javascript"></script>>
<script src="app/app.js"></script>
<script src="app/listView/listView.js"></script>
</head>
<body ng-app="myApp">
<!-- Application content -->
<div ng-include="'app/app.html'"></div>
</body>
</html>
app.html:
<div class="container">
<div ng-controller="appCtrl" ng-cloak class="ng-cloak">
{{greeting.content}}
</div>
</div>
app.js:
angular.module('myApp', [])
.controller('appCtrl', function($scope, $http) {
$http.get('/login/').success(function(data) {
$scope.greeting = data;
});
});
I just get an output like this :
{"id":"01cdab29-e0ce-45ee-abb9-64b2640859ca","content":"Hello
Worl123321"}
and there seems that no angular scripts has been loaded...
What do you use to serialise as JSON ?
This is maybe because of the Map<> that you have an extra field 'content' between your object and your data try.
$scope.greeting = data.content;
I've already heard of some problem like this with Jackson adding a "content" though it was for a hibernate problem.
If you don't want that extra field : create a wrapper class having an id and content field and use it.
function check() {
var svar = document.getElementsByName("svar");
var len = svar.length;
var object = 5;
var jsonData = JSON.parse(JSON.stringify(object));
$.ajax({
type : 'POST',
url : 'http://localhost:9000/postasvar',
dataType : 'json',
contentType : 'application/json',
data : jsonData
});
}
I got the above code in my javascript with the purpose to send a json object to the java.
#BodyParser.Of(BodyParser.Json.class)
public static Result postaSvar(){
JsonNode json = request().body().asJson();
//String svar = json.findPath("svar").textValue();
if(json== null){
return badRequest("förväntade json");
}else{
return ok("hello " + json);
}
}
The java code above is the code that is suppose to handle the json from the javascript but the answer i get is always null.
I also have the following code in my main.scala.html:
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/check.js")" type="text/javascript"> </script>
<script src="#routes.Assets.at("javascripts/hello.js")" type="text/javascript"> </script>
</head>
<body>
#content
</body>
</html>
And this is index.scala.html:
#(message: String)
#main("Welcome to Play") {
#message
<form action="http://localhost:9000/postasvar" method="post">
</br>
<input type="radio" name="svar" value="svar1"/>svar1
<input type="radio" name="svar" value="svar2"/>svar2
<input type="radio" name="svar" value="svar3"/>svar3
<input type="radio" name="svar" value="svar4"/>svar4</br>
<button name="knappen" onclick="check();">Klar</button>
</form>
}
Is it someone who know what the problem might be?
You will need to give a string to jQuery to send and not an object. In your case you get always null because jQuery is not sending anything in the body.
For example, if you do this
$.ajax({
// (...)
dataType : 'json',
contentType : 'application/json',
data : {name: "Salem"}
});
jQuery will send this in the request body
name=Salem
and not the object formatted as JSON (dataType specifies the type of response it is waiting, not the type of data it is sending). So send a string instead:
$.ajax({
// (...)
dataType : 'json',
contentType : 'application/json',
data : JSON.stringify({name: "Salem"})
});
which will send the correct body and work as expected
{"name": "Salem"}
I'm trying out AJAX for the first time. I'm using a Jersey Web Service as what gets called. But my call always executes the error part. Help! please
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Jquery Basic</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#submit1").click(function() {
alert("click");
var username = $("#textbox").val;
$("#para1").text(username);
$.ajax({
type: 'POST',
url: '/FirstProject/src/Resource/resource/welcome',
data: username,
success: function(){alert("Login Success!")},
error: function(){alert("Login Failure!")}
});
alert("ajax passed");
});
});
</script>
</head>
<body>
<a id="body1">JQuery Test Page</a><br>
<div id="heading"><a>Enter Your Details</a></div>
<div>
<div id="heading1"><a>UserName:</a></div>
<div><input id="textbox" type="text"/></div>
<button id="submit1">Submit</button>
</div>
<div><p id="para1"></p></div>
</body>
</html>
WebService is as follows
package Resource;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import POJO.passwordPojo;
import POJO.usernamePojo;
public class resource {
#POST
#Path("welcome")
public String welcomeFunction(#FormParam("username") String username)
{
setUserNameData(username);
return "success";
}
usernamePojo userName = new usernamePojo();
passwordPojo password = new passwordPojo();
public void setUserNameData(String userNameData)
{
userName.setUserName(userNameData.toString());
printuserName();
}
public void setpasswordData(String passwordData)
{
password.setPassword(passwordData.toString());
printPassword();
}
public void printuserName()
{
System.out.println("UserName:"+userName.getUserName());
}
public void printPassword()
{
System.out.println("Password"+password.getPassword());
}
}
Blast!! I know most of my question is code!! Bloody post it already!
Think data needs to be an array.
var usernameVal = $("#textbox").val;
$.ajax({
type: 'POST',
url: '/FirstProject/src/Resource/resource/welcome',
data: { username : usernameVal }
send data as json with index like {"username":username } in ajax data like
....,data: {"username":username },....
I'm trying to make a simple ajax call to a spring REST service I have setup.
My controller is defined as follows:
#Controller
public class SongPlayerController {
....
#RequestMapping(value = { "/ajax", "/ajax/" }, method = RequestMethod.GET)
#ResponseBody
public String ajax() {
return "New Song URL";
}
}
And then I have a simple html page with an ajax request:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
function loadAjax() {
$.ajax({
type : "GET",
url : "http://localhost:8080/song-player/ajax",
data : "text",
success : function(response) {
$('#ajax').val(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
function getAjax() {
$.getJSON('http://localhost:8080/song-player/ajax', function(data) {
alert('Ajax data' + data);
});
}
</script>
</head>
<body>
<button type="button" onclick="loadAjax()">Ajax Call</button>
<div id="ajax">This will be an ajax call.</div>
</body>
</html>
But, neither using the $.ajax or $.getJSON are returning anything. When using the ajax call, I'm getting the error "Error: [object Object]".
However, I know that my controller is setup properly because I can hit my service and get a response by using the RESTClient Firefox add-on so I assume the problem is with how I'm handling the jQuery calls but this is my first attempt at using jQuery so I don't know what is wrong with it.
The string literal "New Song URL" is not valid JSON. Try returning this:
#Controller
public class SongPlayerController {
#RequestMapping(value = { "/ajax", "/ajax/" }, method = RequestMethod.GET)
#ResponseBody
public String ajax() {
return "{\"url\":\"New Song URL\"}";
}
}
Then access this value as follows:
function getAjax() {
$.getJSON('http://localhost:8080/song-player/ajax', function(data) {
alert('Ajax data' + data.url);
});
}
You could use JSON-js's stringify() function as follows:
$.getJSON('http://localhost:8080/song-player/ajax', function(data) {
alert('Ajax data' + JSON.stringify(data));
});
$('#ajax').val(response);
wont work. this is a div. use
$('#ajax').text(response);
thats why loadAjax doesnt work. getAjax doesnt work because as others pointed out, your response is not valid json, so getJSON will not work.
In addition to what others have pointed out about malfomred json, it seems that my problem stemmed from trying to hit my service needed to be called with JSONP.
I ended up modifying the controller to follow this blog post for wrapping my responses with a callback parameter.
I also changed up my ajax call to expecte JSONP:
function loadAjax() {
$.ajax({
type : "GET",
url : "http://localhost:8080/song-player/ajax.json",
async : false,
dataType: "jsonp",
success : function(response) {
$('#ajax').text(response.streamUrl);
alert('Success: ' + response);
},
error : function(e) {
alert('Error: ' + e);
}
}).done(function(data) {
console.log(data);
console.log(data.streamUrl);
});
}
Thanks for all of the help.