jQuery an Yahoo Weather API call failed - javascript

I want to catch weather information. I'm trying to do it with jQuery. So here is my Code:
$(document).ready(function(){
var weatherURL = 'http://weather.yahooapis.com/forecastjson?w=20066287&u=c&callback=?';
$.getJSON(weatherURL, function(data){
//console.log('done');
}); });
It seems that this is working. But it outputs me
Uncaught SyntaxError: Unexpected token :
I think its an JSON validation problem. But all online JSON validation tool passes the test.

It seems the API returns JSON, not JSONP data; getJSON automatically tries to parse it as JSONP is there's a callback query in the URL:
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.
http://api.jquery.com/jQuery.getJSON/
Try this:
$(document).ready(function(){
var weatherURL = 'http://weather.yahooapis.com/forecastjson?w=20066287&u=c';
$.ajax({
url: weatherURL,
dataType: 'json',
success: function(data) {
//console.log('done');
}
});
});

Related

JSONP and Framework7

I'm trying to get images from Instagram public api via ajax and JSONP:
var target = https://www.instagram.com/p/BP3Wu_EDXsjdT5Llz13jFv2UeS0Vw0OTxrztmo0/?__a=1?callback=?';
$$.ajax({
type: "GET",
dataType: 'json',
crossDomain: true,
url: target,
success: function(data){
console.log(data);
},
error: function(xhr,status){
console.log("Error"+status);
}
});
I'm getting: Uncaught SyntaxError: Unexpected token <.
What's wrong?
Thanks
A few mistakes...
var target = 'https://www.instagram.com/p/BP3Wu_EDXsjdT5Llz13jFv2UeS0Vw0OTxrztmo0/?__a=1&callback=';
Changes: Missing ' at the beginning and changed second ? with &
Should work fine
That API with ?__a=1 is undocumented API and does not support JSONP, so you cannot make client side API call using AJAX, you have to make a server side http request and it will work.

Uncaught TypeError: number is not a function when parsing JSONP response in jQuery ajax call

I am trying to grab data from a wordpress blog using the WP-API plugin. My js file is using jQuery to make ajax calls to the api. I need to use JSONP as the response type since I am trying to access cross domain information.
When the page loads, I get an error "Uncaught TypeError: number is not a function" and my response begins like this: /**/1([{"ID":231,"title":blahblahblah... with the error pointing at the "1" in the console.
This is the code I am using to try and grab the data and parse it:
function get_posts(num_offset) {
offset = num_offset,
url = 'http://www.example.com/wp-json/posts?_jsonp=1&filter[posts_per_page]=5&filter[offset]=' + offset;
$.ajax({
type: 'GET',
dataType: "jsonp",
url: url,
success: function (data) {
consol.log(data);
console.log(url);
}
});
// second ajax call to get the total number of posts
$.ajax({
type: 'GET',
dataType: "jsonp",
url: 'http://www.example.com/wp-json/posts?_jsonp=1&filter[offset]=-1',
success: function (data) {
console.log(data);
}
});
}
I guess I need to know how I can remove the "Uncaught TypeError: number is not a function" error and then how I would be able to parse the JSONP data.
much thanks!
You're telling the other end that your callback's name is 1, in your URL:
http://www.example.com/wp-json/posts?_jsonp=1&filter[offset]=-1
Here --------------------------------^^^^^^
You want to use the name of the callback function you have on your page that you're expecting to receive the JSONP response, which needs to be a validate identifier literal (so not 1).
Because you're using jQuery, it's best by far if you let jQuery worry about what the callback name should be, by leaving off that query parameter entirely and letting jQuery add it. Since _jsonp is an unusual query string parameter name for this, you'll need to tell jQuery what the parameter name is.
$.ajax({
type: 'GET',
dataType: "jsonp",
url: 'http://www.example.com/wp-json/posts?&filter[offset]=-1',
// No _jsonp=1 here ------------------------^
jsonp: '_jsonp',
// ^^ new parameter here
success: function (data) {
console.log(data);
}
});

Getting a parseerror from jQuery $.ajax post return using jsonp from Trakt.tv api

Working with the Trakt.tv API. It looks like I'm sending valid json as I'm able to authenticate but the return I receive is a parse error.
Resource interpreted as Script but transferred with MIME type text/html:
http://api.trakt.tv/recommendations/shows/myApiKeyCompleteNumbers?callback=jQuery111000155555475132972_1397674204444&{%22username%22:%22userName%22,%22password%22:%22mySha1PassComplete%22}&_=1397674207093
Uncaught SyntaxError: Unexpected identifier
The return says:
Disallowed Key Characters.
I'm using:
jQuery 1.11.0
Thanks in advance for any help or guidance
$(document).ready(function () {
function success(data) {
alert('data: ' + data);
}
var traktUser = 'myUserName';
var traktHash = 'mySha1Password';
var traktApi = 'myApiKey';
var data = {
'username': traktUser,
'password': traktHash
};
var postData = JSON.stringify(data);
var apiUrl = 'http://api.trakt.tv/recommendations/shows/' + traktApi;
$.ajax({
type: 'POST',
url: apiUrl,
data: postData,
contentType: 'application/json',
dataType: 'jsonp',
}).
done(success);
}); //document ready
You can't make a POST request using JSONP, jQuery is ignoring the POST instruction and making a GET request.
Your data is being placed in the query string and is not properly URL Encoded.
The server is responding with an HTML document containing an error message instead of a JavaScript script formatted according to JSONP rules.
It looks like the API you are trying to use does not support JSONP at all. Since you are passing your own user credentials in the request, this makes sense. JSONP is a hack to work around the Same Origin Policy that is implemented by browsers (these days we can use CORS instead) and there is no point in using it unless you want end user browsers to access the API directly. Since end user browsers couldn't access it without being given your username and password, it doesn't seem likely to be intended to be used that way.
Process the data from the API on your server instead.

Uncaught SyntaxError: Unexpected token : ajax call

So I'm trying to query the below json feed, however I keep getting the error in the topic.
I've searched around this site for possible answers however none that I've come across have worked so far. Commented out datatype and jsonp, jsonpCallback isnt it either, either is data, I've made sure that it validats via http://jsonformatter.curiousconcept.com/ and it does. I really dont know.
$.ajax({
type: 'GET',
url: 'http://raidbots.com/json/playerdata/us/mannoroth/usiris',
cache:true,
dataType: 'jsonp',
data: {
format: 'json',
},
success: ranks,
jsonpCallback:'callbackName',
error: function(data) { console.log(data); },
jsonp: false,
});
function callbackName(data){
console.log("jsonpCallback");
}
var ranks = function(data) {
console.log(data);
}
Thank you
-Art
The error is in your JSONp data because it's just JSON and not JSONp. JSONp requires the document to be valid JavaScript containing a function call.
If they don't support jsonp you need to use a proxy script (e.g. a php script on your server that retrieves the document) or ask them to send CORS headers so you can use a normal non-JSONp AJAX call to retrieve the data directly.

How do i read simple json result with jquery and how to post new

I built a WCF service which produces JSON. I want to make an external website which uses this webservice. For now I am executing the WCF service over LAN by IIS, so I can connect to the service by going to http://myownaddress/blabla.svc/
I tried to learn some json and to get some results from my service.
For example if I want to use this method:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/{id}")]
string JSONData(string id);
I'll go to http://myownaddress/blabla.svc/json/123
And as result I get:
{"JSONDataResult":"You requested product 123"}
Now I have tried to receive this result with the JQuery statement getJSON. But I don't see any results.
My question is how can I get this simple data?
And secondly how can I post data(with javascript) back on to the wcf service is it also possible with json?
-edit-:
I have now updated my code and put this into my document ready function which is located between the <head> <script> .... on my page:
$.getJSON(
'http://myownaddress/blabla.svc',
function(data)
{
alert(data.JSONDataResult);
});
But this won't give the alert with the result. It doesn't even give an alert.. Besides that, in the function I need to give a parameter of id, so for example 123 (look in text above) don't I need to put that in the function also?
To get data use getJSON():
$.getJSON(
'http://myownaddress/blabla.svc/',
function(data) {
alert(data.JSONDataResult);
}
);
To post data you can use this:
$.post('http://myownaddress/postservice.svc', function(data) {
$('.result').html(data);
});
or this (if you need more control):
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You can also use the ajax for getting the data instead of the getJSON method .
UPDATE:
try using ajax method as it gives you more control:
$.ajax({
type: 'GET',
url: "http://myownaddress/blabla.svc/json/123",
success: function(data){alert(data)},
dataType: "json",
complete: function(data){alert(data)},
error: function(jqXHR, textStatus, errorThrown){alert(errorThrown)}
});
Also, if you use firefox, check out firebug extension, it will help you greatly.
If you use chrome then use chrome developer tools.
In order for your to get the json data from a WCF service that is outside your website using Jquery you need to use JSONP.
You can perform the call as shown below:
$.ajax({
url: "http://myownaddress/blabla.svc/",
dataType: "jsonp",
type: "GET",
timeout: 10000,
data: null,
jsonpCallback: "MyCallback",
success: function (data, textStatus, jqXHR) {
alert(action.toLowerCase());
},
error: function (jqXHR, textStatus, errorThrown) {alert('error is:' + errorThrown);
},
complete: function (jqXHR, textStatus) {alert('complete');
}
});
JSONP is used when you want to perform a cross domain calls using Javascript.
Also your WCF service should be compatible to handle JSONP calls by injecting the results to the response stream using the callBack method specified in the URL.
Do you have your code like this ?
$.getJSON(
'http://myownaddress/blabla.svc/',
function(result) {
alert(result.JSONDataResult);
}
);
Remember getJSON will not immediately return you the data, you have to make use of the result in a callback function.
Why did you change your url?
$.getJSON(
'h t t p://myownaddress/blabla.svc' ==> 'h t t p://myownaddress/blabla.svc/123',
function(data)
{
alert(data.JSONDataResult);
});

Categories

Resources