I am trying to access the Stackoverflow API with jsonp as datatype by doing this:
$(document).ready(function(){
$.ajax({
url: 'http://api.stackoverflow.com/1.1/tags/php/top-answerers/month',
dataType: 'jsonp',
});
});
And once I reload, I get the following in the console:
"Uncaught SyntaxError: Unexpected token :"
What am I doing wrong here?
Right now the application is returning Content-Type: application/json.
You can fix this by overriding the callback function name to jsonp which will tell the server to return Content-Type: application/javascript instead:
$(document).ready(function () {
$.ajax({
url: 'http://api.stackoverflow.com/1.1/tags/php/top-answerers/month',
dataType: 'jsonp',
jsonp: 'jsonp',
success: function (data) {
alert(data.top_users.length + ' users retrieved.');
}
});
});
Info on jsonp ajax setting:
jsonpString
Override the callback function name in a jsonp request. This value
will be used instead of 'callback' in the 'callback=?' part of the
query string in the url. So {jsonp:'onJSONPLoad'} would result in
'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
From https://api.stackexchange.com/docs
All API responses are JSON, we do support JSONP with the callback query parameter. Every response in the API is returned in a common "wrapper" object, for easier and more consistent parsing.
So you should use dataType: 'json' rather than jsonp.
You should also upgrade to the 2.1 API, the 1.x API has been deprecated for 6 months.
Related
I use #Html.AntiForgeryToken() to decorate the form and try to send the token in an ajax call, at the beginning I used code below:
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "POST",
url: newurl,
headers: {'__RequestVerificationToken': token},
data: form.serialize(),
datatype: "JSON",
success: function..,
error: function..
})
And it didn't work, server didn't get value I set in the above headers for __RequestVerificationToken, but kept using some old token value.
However, after I switched the "headers" line to the one below, it picked up the token I set.
beforeSend: function (request)
{
request.setRequestHeader("__RequestVerificationToken", token);
},
How come headers doesn't work, but only beforeSend works? So far I couldn't find any clue through online search.
Headers was introduced in jQuery 1.5 and is in the documentation:
https://api.jquery.com/jquery.ajax/
I'm using jQuery 1.11.1, and .Net MVC 5.1.
I set a debugger in jQuery's setRequestHeader method, it turned out that it was called multiple times through the ajax call:
1st:
Content-Type "application/x-www-form-urlencoded; charset=UTF-8"
2nd:
Accept "*/*"
3rd:
__RequestVerificationToken [the token I set]
But it was also called the 4th time, to set __RequestVerificationToken as well:
__RequestVerificationToken [some other token]
By tracking the call stack, I found in our application framework there is a $.ajaxSetup method
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader("__RequestVerificationToken", environment.antiForgeryToken);
}
});
That was the culprit that overwrote the token I set. By using 'beforeSend' in my ajax call, the 'beforeSend' in ajaxSetup is not called.
I'm trying to perform a cross domain call. so i'm using JSONP.
The problem is that the response is not json, but an html.
The request works fine and i see the response with status 200 in the network console, however the error function is the one being called, as the expected response is JSON whereas I get an html.
Do you have alternatives for using JSONP for cross domain request?
If i'm using JSONP but the request is not, can I somehow expect a value which is not a json? (tried dataType: 'jsonp text' and didn't work)
Although I get an error with the ajax call, is there a way to extract the result of the request, as it still returns status 200, it's just not accessible ?
$.ajax
({
type: "GET",
url: myurl,
crossDomain:true,
dataType: 'jsonp',
contentType: "text/html; charset=utf-8",
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
},
});
I am near a solution to get json data, just get the error :
SyntaxError: missing ; before statement
My json data look like this :
{"custom1":"","dateOfBirth":null,"custom2":"","custom3":"","custom4":"","custom5":""}
I am using jsonp. this solved my problem with CORS (Cross-origin request blocked)
In the debugger i can see the data in the NET.
How close i am?
Som get me the last push to resolve my problem??
<script type="text/javascript">
function getdata() {
$.ajax({
type: 'GET',
url: 'http://myurl/api/getUser/22?_key=123456789',
dataType: 'jsonp',
//contentType: "application/jsonp",
success: function (data) {
$('#badge').append(result);
}
});
}
You have to set your ajax response type to jsonp instead of json.
Like
dataType: 'jsonp'
You can read more about it in jquery docs on $.ajax. Also as I can see, the result variable that you are trying to append in the success callback is not declared & inititalized anywhere in the code you have provided.
I am trying to retrieve a JSON from this URL
http://www.iheartquotes.com/api/v1/random?format=json
via jQuery. I know the solution is JSONP, but since I have no control over the response text of the service or to wrap it in my own callback function, my aim is to somehow retrieve the response of the above URL using client-end scripts.
I have tried almost all the methods suggested from several answers from StackOverflow.
These are the code blocks I have tried and the response's I've got.
1 . A direct call which returned the expected Access-Control-Allow-Origin error
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
function(data) {
alert(data);
});
Response:
XMLHttpRequest cannot load
=1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.
Origin http://stackoverflow.com is not allowed by
Access-Control-Allow-Origin.
2 . The above code with the callback parameter added:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
function(data) {
alert(data);
});
Response:
Uncaught SyntaxError: Unexpected token :
Please note that when I click on the error, it takes me to the expected JSON response.
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
This is also expected as there is no callback function defined in the response.
3 . Through jQuery's Ajax method
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://www.iheartquotes.com/api/v1/random?format=json",
success: function(data){
alert(data);
},
});
Response:
Uncaught SyntaxError: Unexpected token :
Adding the callback parameter to the above function doesn't change the response.
Any help or pointers from the experts to retrieve the JSON from the URL? I am testing this from the Chrome Dev Tools. I know I could call the service from the server-end code and then send it across to the client-end. But I want to see if this can be done through jQuery alone from the client-end.
EDIT:
Based on Kevin B's comment:
Got the expected output via YQL using jQuery's Ajax. But my question remains the same. Is there a native way to do it via jQuery as YQL is still a dependency?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
This gives the expected response.
This won't work in all browsers, but depending on which version of JQuery you're using try:
$.support.cors = true;
Obviously this also depends on the headers of the server response.
I'm trying to get data from:
http://api.master18.tiket.com/search/autocomplete/hotel?q=mah&token=90d2fad44172390b11527557e6250e50&secretkey=83e2f0484edbd2ad6fc9888c1e30ea44&output=json
I'm using the jQuery $.ajax method and the code is written in my index.html file:
function getAPI() {
jQuery.ajax({
url: 'http://api.master18.tiket.com/search/autocomplete/hotel?q=mah&token=90d2fad44172390b11527557e6250e50&secretkey=83e2f0484edbd2ad6fc9888c1e30ea44&output=json',
type:"get",
dataType: 'jsonp',
crossDomain: true,
jsonp: false,
success: function(data) { console.log(data); }
});
}
When I try it in the Chrome console, there is a message
Uncaught Syntax Error:Unexpected token:
I am very confused about what the problem is, can anyone help me?
The content being returned is json, not jsonp as you specified in your dataType. Also, by setting jsonp to false, you're preventing a jsonp querystring from being appended to the URL by jquery, which is likely why the API you're using is returning json and not jsonp. I would try taking out the jsonp: false parameter.