I am currently new in Cognitive services. Yesterday I tried Computer vision API where I got different JSON response for the same image in the API Testing console to that when I used the javascript code in my browser. I have enclosed my javascript code and the screenshot of the two different responses.
<!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">
var myKey = "my key";
var myBody = {url:"http://activeforlife.com/wp/wp-content/uploads/2015/05/co-ed-kids-playing-soccer.jpg"}
$(function() {
var params = {
// Request parameters
"maxCandidates": "1",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
document.getElementById("ans").innerHTML = JSON.stringify(data);
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
<h4 id="ans"></h4>
</body>
</html>
Screenshot for the different outputs
The Cognitive Service Vision API will perform different visual classifications depending on the visualFeatures query parameter. You can find more details here.
If you don't specify any features, you are performing the equivalent of visualFeatures=Categories (your example). The console appears to have been executed with visualFeatures=Description. You can set the feature list in your param object.
Related
I have a PHP running on a server, and i call to it via jQuery.Ajax() but it always return to the error portion of it.
If i call the PHP address directly from my browser, i get the response i need, it only breaks in the jQuery call.
The PHP (simply saying) is this:
<?php
if(isset($_GET['getcodenode']))
{
echo json_encode
(
array
(
'itens'=>
array
(
0=>array('id'=>100,'lb'=>'300','ds'=>'300 mm'),
1=>array('id'=>105,'lb'=>'400','ds'=>'400 mm')
)
)
);
die();
}
?>
And on the javascript side i call for it like this:
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>
How to read JSON objects from PHP and display in browser?
There are lots of comments on your code:
While you already getting a json return from server; you don't to parse that. Its already a json object.
You can set async:true to get a promise data
The way you loop through objects you need to do that properly. see image how to get the object path correctly.
You can use $ token instead of jQuery token; unless you purposely need that.
I am not sure if this is the best approach; but it give the needed result as explained in your question.
The code is bellow tested with some comments:
<script type="text/javascript">
loadcall("test");
// as pointed you need to call the function so it runs
function loadcall(data) {
$.ajax({
async: true,
method: 'POST',
crossDomain: true,
dataType: 'json', //your data type should be JSON not JSONP
url: 'page.php?getcodenode',
data: {
'arg': data
},
success: function(result) {
console.log(result);
// see attached image how to get the path for object
var ret = result;
var el = $('#abc');
for (en in ret.itens) {
console.log(ret.itens[en].ds);
el.append('<div id="item_' + ret.itens[en].id +
'">' + ret.itens[en].lb + ', ' + ret.itens[en].ds + '</div>');
}
},
error: function(result) {
console.log(result);
}
});
}
</script>
Open you developer tool in your browser hit F12 (In Chrome, Firefox or Edge):
Go to Console tab and find the results.
Expand the results tell you get to the object you need.
Right click and `copy property path'.
Use the object path as needed in your code.
you need to call loadcall(data)
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
loadcall('somethingData')
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>
I am making a simple chrome application that calls my REST API to retrieve some basic user information in the JSON format. I have the below which in chrome developer tab preview shows to be working, connecting and retrieving what ever I put in my request.
My question is how do I go about dynamically showing on my html page what ever is retrieved?
Ideally I what to just show certain fields only from my response. I.e. just the Name, Location, Contact number as variables I can use throughout my page.
Any pointers would be great. Thanks
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Connect to API</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var authorizationToken = "xxxxxxxxxxxxxx";
function myapiRequest(endpoint, method, options) {
$.ajax($.extend({}, {
type: method,
dataType: "json",
success: function(json) {
items = json;
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
myapiRequest('/users/0H5G?include%5B%5D=contact_methods&include%5B%5D=teams'); // this will be a variable soon
</script>
</body>
</html>
Response 200 OK
{"user":{"name":"john smith Jsmith","email":"john smith #xxxxxxx.com","time_zone":"Asia/Hong Kong","phone":"0123456",}}
$.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts/1',
success: function(response) {
// if your response is in JSON format, you can access response keys
// in the following format (both ways give same result)
var title = response.title; // OR var title = response['userId']);
// ...and then append to the DOM (your HTML) by selecting the
// element you want to append to, and using the append method
$('div.append-to-me').append(title);
},
error: function(error) {
console.log('not implemented');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="append-to-me"></div>
I have an ajax get request that has a data of an input. I want to pass this data into a variable and use it in my query.
index.handlebars
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="hidden" class="test" name="test" value="sample"/>
<script type="text/javascript">
$( document ).ready(function() {
var username = $('.test').val();
$.ajax({
type : 'GET',
url: '/users//welcome',
data : {
wew: username
}
});
alert(username); //correct output
});
</script>
</body>
</html>
and in my users/welcome
router.get('/welcome', ensureAuthenticated, function(req, res){
var test = req.query.wew; //data from ajax request
Item.find({username: test},function(err, docs, test){
//where username is the data
console.log(test);
res.render('welcome', {docs:docs});
});
});
This code is not working. Please help :/
You could use socket.io. I use it for bi-directional communication between the browser and node.js server.
On the client side you would do:
function movePlayer () {
socket.emit ('doSomethingServerSide', {numVal: 4, usrName: 'KaiserSolze'});
}
And server side you would have:
// A FUNCTION THAT LISTENS FOR A CALL FROM BROWSERS CONNECTED VIA SOCKET
socket.on ('doSomethingServerSide', function (msg) {
// THEN YOU COULD REPORT TO ALL BROWSERS / CLIENTS THAT SOMETHING WAS DONE
io.sockets.emit ('reportToClients', msg);
});
If you decide to go this route there are lots of posts here to help you get started with socket.io.
Try giving your website full URL with http and replace double (//) with one
$.ajax({
type : 'GET',
url: 'http://<your application full url>/users/welcome',
data : {
wew: username
}
});
Or you can try below
$.ajax({
url: "/users/welcome?wew="+username,
type: "GET",
contentType: "application/json",
dataType: "json",
});
var test = req.query.wew; //data from ajax request
Just change to this one with this one:
var test = req.body.wew
Also you need to import body parser to your project for getting req.body.keynames
I'm trying to get json data from the Bing Search API.
What I have done is this
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"></script>
<script>
$(document).ready(function() {
var appId = ':mykey';
function getNews() {
//console.log("DF");
var azureKey = btoa(appId);
var myUrl = 'https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27britain%27&$format=json';
$.ajax({
method: 'post',
url: myUrl,
dataType:"jsonp"
//Set headers to authorize search with Bing
headers:{'Authorization':'Basic ' + azureKey }
}
success: function(data) {
console.log("DF");
//console.log(data);
var json = data.d.results[1].Url;
document.getElementById("demo").innerHTML = json;
},
error: function(jqXHR, error, textStatus) { console.error(jqXHR, error, textStatus); }
});
};
getNews();
});
</script>
</body>
</html>
When I try to run this, the following error comes in the console:
Uncaught SyntaxError: Unexpected identifier
for the line
headers:{'Authorization':'Basic ' + azureKey }
I have the following doubts:
Whether I am doing the jsonp thing right?
Whether I am correct in including two scripts:
language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"> and the main script.
And of course, why the error.
The syntax error is a missing comma
dataType:"jsonp",
// ^
You also have an extra } after the headers object, which will be another syntax error, change that to a comma.
headers:{'Authorization':'Basic ' + azureKey }
,
// ^ comma not a }
You won't be able to use the authorization header with JSONP, it is not possible. If the service supports CORS (which it looks like it does) then you can use a normal XHR by setting the dataType to json.
I am writing my first google chrome extension which will use Google's URL shortener api to shorten the URL of the currently active tab in Chrome.
I am a longtime sw developer (asm/C++) but totally new to this "webby" stuff. :)
I can't seem to figure out how to make (and then process) the http POST request using js or jquery. I think I just don't understand the POST mechanism outside of the curl example.
My javascript file currently looks like this:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('chrome.browserAction.onClicked.addListener');
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url;
console.log(tablink);
//TODO send http post request in the form
// POST https://www.googleapis.com/urlshortener/v1/url
// Content-Type: application/json
// {"longUrl": "http://www.google.com/"}
});
});
The easiest solution would be to use jquery's $.ajax function. This will allow you to asynchronously send the content to google. When the data comes back you can then continue to process the response.
The code will look something like this question
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
var result = JSON.parse(response); // Evaluate the J-Son response object.
}
});
Here is the jquery ajax api
Update in Jan, 2016: This no longer works, as the link shortening API requires authentication now.
I wrote a blog post with a simple solution:
http://uihacker.blogspot.com/2013/04/javascript-use-googl-link-shortener.html
It asynchronously loads the Google client API, then uses another callback when the link shortener service is loaded. After the service loads, you'd be able to call this service again. For simplicity, I've only shortened one URL for the demo. It doesn't appear that you need an API key to simply shorten URLs, but certain calls to this service would require one. Here's the basic version, which should work in modern browsers.
var shortenUrl = function() {
var request = gapi.client.urlshortener.url.insert({
resource: {
longUrl: 'http://your-long-url.com'
}
});
request.execute(function(response) {
var shortUrl = response.id;
console.log('short url:', shortUrl);
});
};
var googleApiLoaded = function() {
gapi.client.load("urlshortener", "v1", shortenUrl);
};
window.googleApiLoaded = googleApiLoaded;
$(document.body).append('<script src="https://apis.google.com/js/client.js?onload=googleApiLoaded"></script>');
Here I will explain how to create a google url shortener automatically on every web page using javascript and html
Phase-stages are
1) Make sure you have a jquery script code, if there is already advanced to phase two.
2) Add the following script code, after or below the jquery script code:
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
3) How to use it:
If you want to use html tags hyperlink
<a id="apireadHref" href="blank">blank</a>
If you want to use html tag input
<input id="apireadValue" value="blank"/>
The end result
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
HTML
<a id="apireadHref" href="blank">blank</a>
or
<input id="apireadValue" value="blank"/>
DEMO
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHf3wIv4T',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ "longUrl": "' + longURL +'"}',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
Worked out a quick and simple solution on this issue. Hope it will solve the problem.
<html>
<head>
<title>URL Shortener using Google API. http://goo.gl </title>
<script src="https://apis.google.com/js/client.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
function load() {
gapi.client.setApiKey('[GOOGLE API KEY]');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("result").innerHTML = "";
var Url = "http://onlineinvite.in";
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': Url
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + Url + "<br>";
str += "<b>Test Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("result").innerHTML = str;
}
else {
alert("Error: creating short url \n" + response.error);
}
});
});
}
window.onload = load;
</script>
<body>
<div id="result"></div>
</body>
</html>
Need to replace [GOOGLE API KEY] with the correct Key
Your LongUrl should replace Url value i.e. http://example.com