ajax request to Microsoft Emotion API in javascript - javascript

I am trying to try the microsoft emotion api. I am running a simple python web server with CORS enabled. Below is my server python file with which I start the server:
python-server.py
#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
I have an index.html file in which I am sending the http request:
index.html
<!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() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",JSON.stringify({"my-key"}));
},
type: "POST",
// Request body
data: JSON.stringify({"url": "http://tinyurl.com/2g9mqh"}),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
After about 30 seconds I get the connection refused response. The http request code was taken from the emotion api's page I linked earlier. I wonder whether I need a real server or is there a mistake in the code? Thanks.

The JSON needs to be sent out as a string. So change your body specification to:
data: "{\"url\": \"http://...\"}"

Please use the code below(replace your-key), just save it as a .html and open it in the browser it shut work(without any server). If it works then try it in your python server.
<!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() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","your-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Face API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",
"");
},
type: "POST",
// Request body
data: JSON.stringify({
"url": "http://i1.mirror.co.uk/incoming/article6395000.ece/ALTERNATES/s1200/MAIN-David-Beckham-next-James-Bond.jpg"
}),
})
.done(function(data) {
console.log(data);
})
.fail(function(e) {
console.log(e);
});
});
</script>
</body>
</html>

Related

How to receive judgement result from model of Custom Vision with JavaScript

I want to receive judgement result from model of Azure Custom Vision by using JavaScript.
I changed JavaScript code that this site has.
https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814
But I can't.
What is wrong with my code?
I changed IterationId, application, url, content-Type, Prediction-key, and data.
These part are enclosed with {} in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Human</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
"iterationId": "{Iteration id that showed in Performance Page}",
"application": "{My Project name of Custom Vision}",
};
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Of course, I expected showing "success".
But, the actual output is "error"......
When I changed URL that this site has(https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814) in my code, I can get Success message.
And, I also write
processData: false,
contentType: false,
in ajax in my code
Change your code to see what is the error that you get back:
(Note the new "error" parameter to the request)
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
error: function(xhr,status,error) {
// >>>>>>>>>>>> CHECK HERE THE ERROR <<<<<<<<<<<<
}
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
Once you have the error, it would be easier to help you.

How can I display the data from the JSON on my webpage?

I am writing a script that sends an ajax request. The Cloud seems to response with the JSON, but how can I display the data from the JSON on my webpage?
Here the link for the pretty printed JSON.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<script>
function myFunctionPost() {
jQuery.ajax( {
url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_77877E443B666B7FED2F?$format=json',
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
success: function( response ) {
console.log(response);
},
error : function(error) {
console.log(error);
}
} );
}
</script>
</body>
</html>
To achieve this you can use JSON.stringify() space argument. You will also need to wrap the output with <pre> </pre> will preserve the line spacing.
function myFunctionPost() {
$.ajax( {
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'GET',
success: function(response) {
$('#pp').html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
},
error: function(error) {
console.log(error);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<p id="pp"></p>
</body>
</html>
Source: Does jQuery have a JSON/javascript object to HTML pretty print function similar to PHP's var_dump?
By var responseObject = json.parse(response) to make a javascript object.
And then do as you would with JS object?
Hard to tell exact code without knowing what do you wanna display, in what HTML.

Implementing Microsoft's Project Oxford - Emotion API and file upload

I'm looking to be able to implement the Emotion API from Project Oxford on my website. I've currently written the below HTML/JavaScript code which checks an image from a URL and displays the result of said image after having run the Emotion API:
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
// Request body
data: '{"url": "https://philosophybank.files.wordpress.com/2013/08/happy-people.jpg"}',
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
//console.log(data);
//alert(data.scores);
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
This code works fine, however I'm looking to implement this on my website such that people upload images themselves locally from their machine with the use of a browse button as opposed to looking up an image using the link. Any help would be very much appreciated!
I mocked this up using application/octet-stream as the body type which allows you to post a binary object (i.e. the image itself), rather than a url to an image. The Emotion API documentation details how this is a supported content type.
I've continued with use of JQuery as per your original example.
You should be able to copy and paste this entire example into a HTML file, add your Emotion API key where it says my-key and it will work
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file" name="filename">
<button id="btn">Click here</button>
<script type="text/javascript">
$('#btn').click(function () {
var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: file,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
alert(error.getAllResponseHeaders());
});
});
</script>
</body>
</html>

No response in html page call to web api

i am trying to call c# web api but there is no response in html page but i getting response in cshtml
WEB API CODE
namespace MvcApplication3.Controllers
{
public class StoreController : Controller
{
public string Get2()
{
return "response data";
}
}
}
HTML CODE
<html>
<head>
<script src="jquery-1.8.2.js">
</script>
<!--<script src="jquery-1.8.2.min.js">
</script>-->
<script type="text/javascript">
$(function () {
$(document).ready(function () {
$('body').on('click', '.test', function (e) {
alert('a');
jQuery.support.cors = true;
$.ajax({
// url: 'http://localhost:3595/api/values/5',
url: 'http://localhost:1152/Store/Get2',
type: 'GET',
dataType: "Jsonp",
success: function (data) {
alert(data);
}
});
});
});
});
</script>
<title>
</title>
</head>
<body>
<input type="button" value="submit" class="test"/>
</body>
</html>

Project Oxford - HTTP 404 when calling Computer Vision API through Javascript

I am trying to get JSON data from Microoft Project Oxford through a API call. I followed the API reference but when I make a call I get a 404 error.
<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
"visualFeatures": "All",
};
$.ajax({
url: "https://api.projectoxford.ai/vision/v1/analyses&" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","0000000000000000");
},
type: "POST",
// Request body
data: '{ "Url": "http://www.sweetheartmotors.ca/sites/default/files/audi_PNG1736.png" }',
})
.done(function(data) {
alert("success");
//display data
console(data);
})
.fail(function() {
alert("error");
});
});
</script>
What is stopping me from making the call?
You need to change the URL to end in a question mark, rather than an ampersand: https://api.projectoxford.ai/vision/v1/analyses?
Unfortunately most of the samples on the projectoxford.ai site contain this error.

Categories

Resources