Authorization headers error while getting jsonp - javascript

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.

Related

Not getting a response for an AJAX call to PHP (with JSON data)

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>

Different response in my browser vs the API Testing Console

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.

Why isn't this jquery.get function working?

I've been trying to create a small page and all it does is update some values from a source document. The page loads fine, but I don't get the results from the requested source. The .fail function runs, but the textStatus and errorThrown values don't appear in the alert() window that pops up.
I'm very new to javascript and jquery. I'm trying to bash this together with pieces found from the web to figure it out but nothing seems to be working. Mainly, it's the response I think I'm falling down on...
Anyway, here's the code:
<html>
<head>
<title></title>
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function update() {
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890/linearlist.xml",
dataType: "xml"
}).done(function (res) {
//alert(res);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
}
function GetData() {
update();
setTimeout(function () {
GetData();
}, 50);
}
});
</script>
</head>
<body>
<script type="text/javascript">
GetData();
</script>
<div class="result"> result div</div>
</body>
</html>
UPDATE:
I've update my code re: #Ian's answer. It's still not working, sadly. I'm not getting the textStatus or errorThrown results either. I've tried debugging with Internet Explorer through VS2012 but it's not getting me far. If I put the URL into a webpage, I can view the XML document.
$.get does not accept one parameter as an object literal; it accepts several: http://api.jquery.com/jQuery.get/#jQuery-get1
You might be thinking of the $.ajax syntax: http://api.jquery.com/jQuery.ajax/
Anyways, call it like:
$.get("http://192.168.2.86:15890//onair.status.xml", {}, function (res) {
var xml;
var tmp;
if (typeof res == "string") {
tmp = "<root>" + res + "</root>";
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(res);
} else {
xml = res;
}
alert("Success!");
}, "text");
Or use $.ajax:
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890//onair.status.xml",
dataType: "text"
}).done(function (res) {
// Your `success` code
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
Using the fail method, you can see that an error occurred and some details why.
Depending on what/where http://192.168.2.86:15890 is, you may not be able to make AJAX calls due to the same origin policy - https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript
I know you have some logic in your success callback, but I'm pretty sure if you specify the dataType as "text", the res variable will always be a string. So your if/else shouldn't really do much - the else should never execute. Either way, if you're expecting XML, it's probably easier to just specify the dataType as "xml".

Syntax error while running node.js file

Folks I am working on the Editinplace functionality and while running I get this error on the chrome console Uncaught SyntaxError: Unexpected token < I am doing this with the node.js snippet as follows
case '/':
res.writeHead(302,{'location':'http://localhost/editinplace/index.html'});
res.end();
break;
case '/save':
console.log("called");
console.log("Inside called");
res.write('_testcb(\'{"message": "Hello world!"}\')');
res.writeHead(302,{'location':'http://localhost/editinplace/save.html'});
res.end();
break;
The code for the index.html is as follows
<script type="text/javascript">
$(document).ready(function(){
setClickable();
});
function setClickable() {
$('#editInPlace').click(function() {
var textarea = '<div><textarea rows="10" cols="60">'+$(this).html()+'</textarea>';
var button = '<div><input type="button" value="SAVE" class="saveButton" /> OR <input type="button" value="CANCEL"class="cancelButton" /></div></div>';
var revert = $(this).html();
$(this).after(textarea+button).remove();
$('.saveButton').click(function(){saveChanges(this, false);});
$('.cancelButton').click(function(){saveChanges(this, revert);});
})
.mouseover(function() {
$(this).addClass("editable");
})
.mouseout(function() {
$(this).removeClass("editable");
});
};//end of function setClickable
function saveChanges(obj, cancel) {
if(!cancel) {
var t = $(obj).parent().siblings(0).val();
var data=t;
$.ajax({
url: 'http://localhost:9090/save',
type:"GET",
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: true,
timeout: 1000,
data:{data:JSON.stringify(data)},
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
}
else {
var t = cancel;
}
$(obj).parent().parent().after('<div id="editInPlace">'+t+'</div>').remove() ;
}
</script>
</head>
<body>
<div id="editInPlace">Nilesh</div>
</body>
The save.html is a simple text enclosed in <pre>tags.And the error is shown to be in save.html line 1.Thankx for your efforts.
OK, so here's what happens:
browser loads index.html
user edits the field and clicks save
saveChanges makes an AJAX GET request to /save
Your server code sends an HTTP response with a 302 status code and a jsonp body
I think that the browser is transparently handling the 302 status code and ignoring the body
Thus your jquery code is expecting your javascript from the response body of /save, but it's really getting the HTML from /save.html. That's where the syntax error happens, when jquery tries to evaluate that HTML as javascript because you told it the dataType was jsonp.
See also this question about browsers handling redirects automatically
The solution is you need to send a 200 response code so jquery can do the jsonp thing and then after that you can change window.location to /save.html if you like.

Using javascript to access Google's URL shortener APIs in a Google Chrome extension

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

Categories

Resources