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.
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
in the belwo code "code_2" I have a controller that applies http method DELETE, to remove a specific product based on the provided id.
in "code_1", I am trying to create ajax call that shows or present to the user a dialog or pop-up with YES and NO BEFORE the controller in code_2 is executed. in other words, when the client call
/product/remove/2
he should be presented with a popup or dialog with YES and No. When he clicks YES, then the controller in code_2 should be executed normally. If he click NO, nothing should happen..only the dialog or the pop-up disappears.
For the pop-up or the dialog, I did the following as shown below:
<body>
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go" onclick="return confirm('Are you sure you want to search Google?')"/>
</form>
</body>
i could not not find a form with YES and NO buttons...can you help me to correct it
I have implemneted the below code_1 and code_2.
please let me know if the code is correct or needs to be modified...i do not have access to server moreover, I am new to ajax and spring mvc technologies.
code_1:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax confirm delete prodcut</title>
<script
src="${pageContext.request.contextPath }/resources/js/jquery-1.6.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#confirmremoveform').click(function() {
var idx = $('#idx').val();
var ans = confirm("Are you sure you want to delete this Record?");
if (ans) {
$.ajax({
type: "DELETE",
url: "/product/remove/" + idx,
dataType : 'json',
contentType : 'application/json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#onsuccessfuldelete").text(data);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
});
}
</script>
</head>
<body>
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go" onclick="return confirm('Are you sure you want to search Google?')"/>
</form>
</body>
</html>
code_2
#Controller
#RequestMapping("/product/remove")
public class RemoveProductPageController {
public final static String sRemoveProductFromListAttributeName = "removeProductFromList";
public final static String CONTROLLER_URL = "/product/remove";
public final static String DO_REMOVE_HANDLER_METHOD_URL = CONTROLLER_URL + "/{idx}";
#Autowired
private ProductService productService;
#RequestMapping(value = "/{idx}",
method = RequestMethod.DELETE)
#ResponseBody
public ResponseEntity<String> doRemove(#Validated #Size(min = 0) #PathVariable(required = true) int idx,
Model model) {
Product productToBeRemove = productService.getProductFromListByIdx(idx);
if (productToBeRemove == null) {
return new ResponseEntity<String>("no product is avaialble at index:" + idx, HttpStatus.NOT_FOUND);
}
model.addAttribute(RemoveProductPageController.sRemoveProductFromListAttributeName, productToBeRemove);
productService.removeProdcutFromListBxIdx(idx);
return new ResponseEntity<String>("product removed from index: " + idx, HttpStatus.OK);
}
}
Try using SWAL(SweetAlert). It is a customizable replacement for javascript popups.
There are a lot of options you can choose from.
Example:
JSP,
On click of your delete button
$('#[idOfDeleteButton]').click(function (e) {
e.preventDefault();
swal({
title: 'Are you sure you want to delete this record',
type: 'warning',
showCancelButton: true
}).then(function () {
//execute once user confirms else nothing happens
var deleteLink = "[link to controller]?id="+[idTobeDeleted];
$.ajax({
url: deleteLink ,
contentType: "application/json",
type: 'GET',
success: function (res) {
//res is the string returned in the controller
if (res === "Success!") {
swal({
title: res,
text: "Delete Successful!",
type: 'success'
});
} else {
swal({
title: res,
text: "Deleting record Failed!",
type: 'error'
});
}
}
});
});
});
I'm calling my Java Servlet with an AJAX call, but I'm not able to read the input parameter from the request. I've tried two ways but with no luck:
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: id,
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
And:
id = 1;
$.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', {
reqValue: id
}, function(responseText) {
// $('#welcometext').text(responseText);
alert("OK!!!");
});
My servlet code is a simple log print of the request parameter, but the return value is always null:
String reqID = "";
log.info("Servlet called");
reqID = request.getParameter("reqValue");
log.info("reqID = " + reqID);
How can I get this working?
The only way I've found to get the code working is manually add the parameter to servlet url, like http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1
i have check you code.this is my working code.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var id;
function fun() {
alert("aaaa");
id = 1;
$.ajax({
type : "POST",
data : {
reqValue : id
},
url : "/WebProject/callAjax"
});
}
</script>
</head>
<body>
<button id="scan" onclick="fun()">Sacn</button>
</body>
</html>
//Servlet
#WebServlet(urlPatterns = {"/callAjax",})
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("reqValue"));
}
}
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: { reqValue : id},
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
There are different methods you need to override in servlet. Those are doPost(), doGet(), service() and etc.
I suspect you are using doGet() method that's why when you add parameter to the URL your java code is working and in other two cases as you are using type : "POST" java code is unable to read the data from Request Body( in post method the data will be added to Request Body).
I suggest you to use doPost() or service() methods instead doGet().
I am using a java based adapter in worklight. I have a method which returns a string value. I am able to call the function and the result is going to success handler in the adapter, but i am not able to find out anything about the return value. I cant see the returned String anywhere in the response JSON. Can anyone help me with this?
Here is my response JSON:
{"status":200,"invocationContext":null,"invocationResult":{"responseID":"16","isSuccessful":true}}
I have seen the following example
http://public.dhe.ibm.com/ibmdl/export/pub/software/mobile-solutions/worklight/docs/Module_05_5_-_Using_Java_in_Adapters.pdf, when i do an "invoke Adapter Procedure" on the code sample, I am getting this result.
{ "isSuccessful": true, "result": -9 }
where result is the return value of the java method in the adapter.
But when i do the same thing for my app, i get the following
{ "isSuccessful": true }
Java-adapter.impl code
function getXML() { return {result:
com.worklight.javaCode.FileIOPlugin.getXML() }; }
Java class method
public class FileIOPlugin{
public static String getXML() {
return "SUCCESS";
}
}
function getXML()
{
var invocationData ={
adapter: 'JavaAdapter',
procedure: 'getXML'
};
WL.Client.invokeProcedure(invocationData,{
onSuccess: successHandler,
onFailure: failureHandler
)};
function successHandler(data) {alert(JSON.stringify(data));}
function failureHandler(data) {alert("Error to get data");}
The return needs to be an object.
I've tried to reproduce your problem in the recently released Worklight 6.0, and I see everything working fine, after a copy&paste of your code.
The only change I did was to add the empty parameters on the invocationData object used to invoke the adapter method.
This is my exact code:
FileIOPlugin.java (under server/conf, in a package com.worklight.javacode)
package com.worklight.javacode;
public class FileIOPlugin {
public static String getXML() {
return "SUCCESS";
}
}
JavaAdapter.xml (HTTP adapter definition, under adapters folder)
<?xml version="1.0" encoding="UTF-8"?>
<wl:adapter name="JavaAdapter"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.worklight.com/integration"
xmlns:http="http://www.worklight.com/integration/http">
<displayName>JavaAdapter</displayName>
<description>JavaAdapter</description>
<connectivity>
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>http</protocol>
<domain>rss.cnn.com</domain>
<port>80</port>
<!-- Following properties used by adapter's key manager for choosing specific certificate from key store
<sslCertificateAlias></sslCertificateAlias>
<sslCertificatePassword></sslCertificatePassword>
-->
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="2" />
</connectivity>
<procedure name="getXML"/>
</wl:adapter>
JavaAdapter-impl.js (next to JavaAdapter.xml)
function getXML() {
return {
result : com.worklight.javacode.FileIOPlugin.getXML()
};
}
I called my app javaAdapterApp, hence these file names:
javaAdapterApp.js (under apps/javaAdapterApp/common/js)
function wlCommonInit(){
}
function getXML() {
var invocationData = {
adapter : 'JavaAdapter',
procedure : 'getXML',
parameters : []
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : successHandler,
onFailure : failureHandler
});
}
function successHandler(data) {
alert(JSON.stringify(data));
}
function failureHandler(data) {
alert("Error to get data");
}
And finally
javaAdapterApp.html (under apps/javaAdapterApp/common)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>javaAdapterApp</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link rel="stylesheet" href="css/javaAdapterApp.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body id="content" style="display: none;">
<button onClick="getXML()">GET XML</button>
<script src="js/initOptions.js"></script>
<script src="js/javaAdapterApp.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
I ran it in the test server, and the result of JSON.stringify(data) in the success handler looks like:
{"status":200,"invocationContext":null,"invocationResult":{"responseID":"9","result":"SUCCESS","isSuccessful":true}}
There is the "SUCCESS" String you are looking for in the invocationResult.result.
Hope this helps
Orlando
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 ?