Cannot get JSON data from URL - javascript

Apologies for asking what looks like a frequently asked question but I cannot seem to be able to get the data from the following URL: http://www.strava.com/stream/segments/860503
I have tried the following:
$(document).ready(function() {
$.ajax({
url: "http://www.strava.com/stream/segments/860503&callback=?",
dataType: "json",
success: function(data) {
$(document.body).append(data.latlng);
}
});
});
And:
$(document).ready(function() {
$.getJSON("http://www.strava.com/stream/segments/860503&callback=?", function(data) {
$(document.body).append(data.latlng);
});
)};
But I am not having any luck. I have fiddled around with 'json' and 'jsonp', adding the '&callback=?' to the URL as well as other things suggested on SO, but to no avail.
Any help is greatly appreciated.

That particular URL does not support JSONP. Neither does it provide support for Cross Origin Resource Sharing (CORS) via the Access-Control-Allow-Origin response header, therefore it is impossible to directly call it via ajax.
The requirement for JSONP support is that the server must output the callback name as a function, passing the JSON as a JavaScript object or array in the argument to the function. For example:
myCallback({ ...... });
A possible solution is to proxy the ajax request through a server side script on the same domain, where cross origin is not a problem for server to server requests.

the data from "http://www.strava.com/stream/segments/860503" has no callback. it is not made for cross-domain. if your script is on the same server use:you have acces to the php of the server use echo $_GET['callback'].'('.json_encode($return) .')';
else try to use [php] cURL;

please watch This Side Example I think usefull for you
http://demos.jquerymobile.com/1.0a2/experiments/api-viewer/docs/jQuery.getJSON/index.html

have you tried ? The difference being the cb instead of ? at the end of the URL.
$(document).ready(function() {
$.getJSON("http://www.strava.com/stream/segments/860503?callback=cb", function(data) {
$(document.body).append(data.latlng);
});
)};

Related

How to get JSON Object from URL

I'm very new to web development.
When I input this link
https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412
into my browser, I can see the JSON object.
What do I need to do so can I use this JSON object in my javascript? I've tried using JQuery's $.getJSON with no luck.
EDIT
Using JSONP worked! Appending &jsonp=readJSON&?callback=? to the URL gave me back the JSON I wanted. Thank you for all the informative answers.
$.getJSON( "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412&jsonp=readJSON&?callback=?", function() {
console.log( "success" );
})
function readJSON(response){
console.log (response);
}
The question is, is this domain (api.locu.com) the same from where you serve your files? I suppose it isn't. In this case, you have two options:
Your backend can proxy the request from this site
You have to use a JSONP object if it's supported by the API
I'm no clear about your question, but I think you can use a call ajax, something like:
$.ajax({
url: "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412",
type: 'get',
cache: false,
success: function (response) {
console.log(response);
}
});
This should get the concept across if you are using JQuery... but you can use just about anything.
var url = "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412";
var result;
var settings = {
success: function(data){
result = data;
//do anything else related to this data here as you need it fetched, and is not linear.
}
}
$.ajax(url, settings);
Now, I noticed you used getJSON, which is pretty much the exact same. I did not however see you use a success function, so if you did your way, have you tried:
$.getJSON(url, function(data){
result = data;
});
I may be mistaken, but you say: "With no luck" so i have a limited understanding as to what you tried with $.getJSON
Not directly from inside a web browser, no. You would need to use a proxy: another server that makes this request in your behalf and then gives you the result.
Why not?
Web browsers are pretty tight on security. One of the strategies for protecting users from malicious activity is restricting the domains your Javascript can make HTTP requests to.
An HTTP request from your domain (the origin) to another domain is called a cross-origin request. These are forbidden by default, and you won't be able to read the response body, unless the received HTTP response includes the header Access-Control-Allow-Origin.
How then?
By using a proxy as an intermediary. The proxy is not a web browser, it doesn't care about Access-Control-Allow-Origin, and will read the response anyway.
There are a number of proxies you can use. An easy one is YQL (the Yahoo Query Language). Here's an article on the topic, using jQuery: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax

Getting 'data is null' on a Twitter API call but displays data in browser

I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});

How do I pass or parse that access_token from the Dom to a Variable I can then Store and call for access_token?

With help from others I've gotten to the point where I can see the json return from foursquare but any attempts to call it yield an error.
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Try removing the "&callback=?" from the url. I think jQuery adds that for you if you set the dataType to jsonp.
EDIT:
from the jquery ajax documentation describing the dataType parameter:
"jsonp": Loads in a JSON block using
JSONP. Will add an extra "?callback=?"
to the end of your URL to specify the
callback.

JQuery ajax call to cross-domain webservice

I would like consume cross-domain web-service from client with jquery
function TestService() {
$.ajax({
url: "http://service.asmx/GetGeoCompletionList",
data: { "prefixText":"eka", "count":"10", "contextKey":"Trace_0$Rus" },
dataType: "jsonp",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.statusText);
}
});
}
At the error hander I have:
textStatus=parseerror
XMLHttpRequest has status 200 and readyState 4
errorThrown is jQuery16103495572647140...78197139 was not called
I've spent on it for a lot of hours and couldn't make it work. Can u help me?
UPDATED
Thanks, I change to GET, and fix my data string.
Service returns valid JSON object. I can see it at firebug on other site, which consume this service. But that site is getting common json(since it has one domain).
So, if the web-service returns valid JSON(not jsonp), I can't use the same method with jsonp? What can I do for consiming json web-service from other domain?
That string you are passing and claiming is JSON isn't JSON.
Only " characters may be used to quote strings.
Also, you can't make a cross domain JSON-P POST request.
You cannot do cross-domain POST requests using JSONP. JSONP works by adding script tags to the page. script tags always fetch their source using GET HTTP requests. You won't get any data posted.
Summary of problems:
Make sure you're using valid JSON
as #Quentin mentioned.
Make sure you're using GET requests, as
#lonesomeday mentioned
Make sure the response from the server is
JSONP, as seen here

Error when calling webservice with jquery

I have read a lot about jquery and i have a webservice where i convert a companyID to the real companyName. Now i want to call that webservice with jquery or javascript. The webservice is on host http://webservice/service.asmx en i'm working on http://tlmos. I don't work and i always get an error
Here is my code:
<script type="text/javascript" src="http://kmosvi24/_layouts/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var test = "KBEACDNV";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://webservice/service.asmx/getCompanyByCompanyID",
data: "{'sCompanyID:' + 'test'}",
dataType: "json",
succes:function(response){ alert("good"); },
error: function(response) { alert("Uh oh"); },
complete: function(response) { alert("" + response); }
});
</script>
Can someone help me?
thx
Umm.. you spelled success wrong on line 11
.. and you probably want to format your data as
data: "sCompanyID=test"
Take a quick pass through the jQuery API page on this one to verify you are passing the parameters that your service expects. It looks like you are expecting a SOAP packet with an ASMX service, and jQuery is more suited to hitting a restful service generated from an ASHX file or WCF service.
You can make a request to a different server, but only if the call uses GET. Since all you do is lookup anyway, a GET request should be fine.
As some othe people have pointed out you cannot call a webservice on another domain, however as you are using ASP.NET, you can write a raw HTTP handler (normally with an .ashx extension to proxy your request from client to server.) Which you'd place on your "timos" server
so in your ashx file you can write something along the lines of...
public void ProcessRequest (HttpContext context)
{
XmlDocument wsResponse = new XmlDocument();
string url = "http://webservice/service.asmx/getCompanyByCompanyID?CompanyID="
context.Request.Form["CompanyID"].ToString()
wsResponse.Load(url);
string XMLDocument = wsResponse.InnerXml;
context.Response.ContentType = "text/xml";
context.Response.Write(XMLDocument);
}
Hope this helps.
You can't do AJAX calls to hosts other than your own. If you really have to do this make a call to your own server and use a simple proxy to redirect to the domain you need.
You could do this for example by using a ProxyPass-directive in your webserver:
ProxyPass /service/ http://webservice/service.asmx
ProxyPassReverse /service/ http://webservice/service.asmx
Then you can issue an AJAX-request to /service/getCompanyByCompanyID and it will be proxied to the correct URL.
I don't think you are using the data parameter right, usually it's a key-value pair like:
data: {sCompanyID: 'test'}
I believe that they way you are using it will result in jQuery attempting to post to http://webservice/service.asmx/getCompanyByCompanyID?sCompanyID:blah
Also aren't .NET web services SOAP? I don't think jQuery can parse that...
edit: Nevermind, didn't realize you were passing these as json data. Thanks commenters!
In order to run your web-services from Jquery, you should use either WCF or just usual web services, but you should add [ScriptMethod] to your service's method and [ScriptService] to your webservice description.
Wow wow
just noticed that you're trying to call the service from one host to another... that one won't work. service should be hosted on the same domain as the page where it's being called from.
as a reply to Jeff's answer, correct way to format data is data: {key: "value"}
With jQuery Ajax Requests you need to use the following format when defining the variables to be sent in the request:
data: "variableName=variableContent",
You wrote:
data: "{'sCompanyID:' + 'test'}"
This won't work for two reasons:
- You have included curly brackets which don't need to be there.
- You have used a semi-colon,":", instead of an equals sign,"=".
So long as you change these it should work.
P.S I only just realized that Jeff Fritz has already given you the right answer. His answer is spot on!

Categories