How to verify two Images using Azure Cognitive Face API in JavaScript - java

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

Related

Getting 400 bad request error in Jquery Ajax POST in jsp file

I am performing simple crud operation during this I am getting 400 bad request error on console
i.e. POST http://localhost:8080/student/getDetails 400
my code :
<body>
<form >
Enter Student id: <input type="number" id="id" name="id"/><br/>
<button id="selectButton" onclick="getStudent()">Get Student</button>
</form>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function getStudent() {
$.ajax({
type: "POST",
url : "/student/getDetails",
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data)
{
alert(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
</body>

Cant get json from the javascript to the java in play

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

How to print google-annotated-chart by clicking on print button, just like normal print as save it as a pdf programatically?

How to print Google annotated chart by clicking on print button in a web page?
In my code, I used window.print() method, but when I print the page, chart disappears from the webpage and rest of the content is printing.
Please help me.
<!DOCTYPE html> <html> <head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"><!--
css for datepicker -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><!--
Javascript for datepicker -->
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]}); $(document).ready(function(){
showGoogleChart('2013-12-01','2013-12-31');
//============================= Onpage load calling chart function
$( "#from" ).datepicker({ changeMonth: true,
dateFormat:'yy-mm-dd', numberOfMonths: 3, onClose: function(
selectedDate ) { $( "#to" ).datepicker( "option", "minDate",
selectedDate ); } }); $( "#to" ).datepicker({
dateFormat:'yy-mm-dd', changeMonth: true, numberOfMonths: 3,
onClose: function( selectedDate ) { $( "#from" ).datepicker(
"option", "maxDate", selectedDate ); } }); });
//==================== OnChange date call google chart
================== function getChartdate(){ alert("hi"); var startdate = $('#from').val(); var enddate = $('#to').val();
showGoogleChart(startdate,enddate); //===========On button click
calling chart function========= }
function showGoogleChart(startdate,enddate){
var queryObject="";
var queryObjectLen="";
var postdata = {"startDate":startdate,"endDate":enddate};
$.ajax({
type : 'POST',
url : 'testPages.jsp',
data:postdata,
dataType:'json',
success : function(data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
google.setOnLoadCallback(drawChart(queryObject,queryObjectLen));
},
error : function(xhr, type) {
alert('server error occoured')
}
});
}
function drawChart(queryObject,queryObjectLen) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'date');
data.addColumn('number', 'temp');
for(var i=0;i<queryObjectLen;i++)
{
var name = queryObject.empdetails[i].date;
var empid = queryObject.empdetails[i].temp;
data.addRows([
[name,parseInt(empid)]
]);
}
var options = {
title: 'Employee Information',
}; var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options); }
</script>
</head>
<body>
<div style="margin: 50px;">
<label for="from">From</label> <input type="text" id="from" name="from"> <label for="to">to</label> <input type="text"
id="to" name="to"> <input type="button" id="changeChart"
onclick="getChartdate();" value="Change Chart"/>
</div>
<div id="chart_div"></div>
</body>
</html>
The method window print() will simply open the print dialog. How the page is formatted for print depends on how the browser formats webpages and the print stylesheet if present.
Assuming the chart is some kind of image (or canvas), it might be that the browser choses to strip images when printing. Especially if the image is added using css background-image: url(...) because it assumes a background image (like background-color) is just for decoration and would waste ink if printed.
A plain img tag should print though in most cases unless some css is removing it for print...

play framework 2.0 json - receiving null JsonNode object

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 ?

Ajax Call To Spring Service

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.

Categories