I'm trying to get data from an API with javascript but i'm getting an error on the request.
$.ajax({
dataType: "jsonp",
url: "https://www.bitstamp.net/api/ticker/",
type: "GET",
succes: myfunction
});
result:
{"error": "GET parameters not allowed for this request."}
I use Jsonp because its another domain.
Why can't I get the data with Jquery?
If I just browse to the link I can see the Json.
I just tried getting data from the url you provided using AJAX. The server did not return any data using the $.ajax and this clearly shows that the server does not support cross domain requests. That is why I asked you if you had access to code because you have to manually specify if you want API to support cross domain requests.
One way around to this is using some server side language to access this API. I once had similar problem and the used PHP CURL to access the API. The php code then served data to JQuery to be used on frontend. So you can write relay code to solve this problem.
Because, as the error message says, bitstamp do not allow it.
If they get a JSONP request for the data, they respond with the error instead of the normal response.
Related
I've seen many examples for JSONP but I can't seem to get any to work for my website. It can generate a JSON code at some url but I can't retrieve it from a different domain. Can you please give me a working example of JSONP that can retrieve data from any JSON file (eg. www.w3schools.com/json/myTutorials.txt).
I may not fully understand, but I just need an explanation, at least, of why if I replace a url with the example above, no data is being pulled.
This is a modified version of the example in the jquery docs using Yahoos public APIs.
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell YQL what we want and that we want JSON
data: {
q: "show tables",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
Along with a jsbin: https://jsbin.com/tuketa/edit?js,output
The reason for the existence of JSONP is to get around the limitations of CORS rules. For security reasons your browser, in general, is only allowed to communicate to the server it loaded the page from. JSONP was created to get around this by giving the server a callback function with which to pad the JSON data, hence the P in JSONP.
As noted in the comments by jasonscript, it's not any server that can function with JSONP, it has to be configured be able to work with JSONP such as the Yahoo API in the example.
There's many answers out there pointing out the difference between JSON and JSONP. Your question ("...jsonP that can retrieve...") shows that you didn't fully understand the concept. JSONP is a format of answer, as is HTML, XML, JSON. And so the server that responds the request should be able to send it JSONP formatted.
from a different domain... from any json file... it's not possible. The server response it's actually a javascript that wraps a json object.
jsonP is a protocol. the requester (the javascript in the browser) can't request via XHR (ajax) outside the source server:port due the Same-Origin-Policy (SOP).
To bypass the SOP, JSONP born.
The client does not send a XHR request, instead adds a <script> tag to the DOM, with the src attribute pointing to the URL of the jsonP with a parameter (e.g. callback=foo) which tells the name of the local function who receives the JSON as parameter.
Then, the remote server -who understands JSONP- sends a javascript who calls the local function with the JSON as parameter.
Like this example:
Client javascript code:
function foo(data)
{
// do stuff with JSON
}
var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
(taken from here)
Server Response:
HTTP/1.1 200 OK
Content-Type: text/javascript
foo({ "key" : "value" });
So, the browser loads the script, calls foo with the json as parameter. Now, You have bypassed the SOP restrictions.
I've been stuck on consuming a web service created in PHP, not sure what I'm doing wrong.. Ive created a fiddle example here : http://jsfiddle.net/e97AV/
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error.. in the browser when I visit the url it is returning valid json
My question is how would I know when to use jsonp or json? Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
heres the ajax code
baseUrl = "http://exclusivegetaways.co.za/api.php";
$.ajax({
type: "GET",
url: baseUrl,
data: {something : "something"},
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("works");
alert(result);
},
error: function (a,b,cc) {
alert(a+b+cc);
}
});
I've since been able to pull json data from the ajax error object?? like so:
baseUrl = "http://exclusivegetaways.co.za/api.php?something=something";
$.ajax({
type: "GET",
url: baseUrl,
dataType: "json",
success: function (res) {
alert("worked");
//alert(res);
},
error: function(jqxhr) {
try {
f = JSON.parse(jqxhr.responseText);
...valid json returned here
} catch(err) {alert(err);}
}
});
This is because of a security restriction that prevents Ajax from querying remote locations.
As a workaround to enable access to a remote location via Ajax, you could build a custom URL in your webApp (in PHP for instance) which queries the distant API and returns JSON.
Then, in your JavaScript, you call this URL (from your application) via Ajax.
First: Always look at your JavaScript error console.
XMLHttpRequest cannot load http://exclusivegetaways.co.za/api.php?location=provinces.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access.
See also Ways to circumvent the same-origin policy
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error. in the browser when I visit the url it is returning valid json
This suggests that:
They don't support JSONP
They look at the HTTP headers and 404 your request to block access from Ajax (this isn't a good way to do that, the error code is misleading)
My question is how would I know when to use jsonp or json?
Usually by reading the documentation for the server you are trying to use
Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
Usually by working with whatever support is provided by the API provider (i.e. start with their documentation, then fall back to whatever means they provide for communicating with a human).
Due to Same Origin Policy your ajax request is allowed only if:
domain name, application layer protocol, and (in most browsers) port
number of the HTML document running the script are the same
In your case the application layer protocol is different, that's why your script fails.
Possible solutions are:
JSONP, which has to be provided by the server
CORS, which is a more 'elegant' and clean solution, but is not yet fully supported by IE (IE7 doesn't support it, IE8 has some limitations)
Answer taken from this link
I'm working on an application which use ajax call to get html from the server.
When I run it on the server, everything works fine.
But when I'm running on a localhost, I've a 'Access-Control-Allow-Origin' error.
I looked arround and it seems like using jsonp could be the solution.
So, my ajax call looks like that:
$.ajax({
url: url,
dataType: 'jsonp',
crossDomain: true,
type: 'GET',
success: function(data){
// should put the data in a div
},
error: function(){
//do some stuff with errors
}
});
I get html from the server, but I always have this error:
Uncaught SyntaxError: Unexpected token <
Is there a way to wrap the jsonp response in html?
Thanks!
You can't use JSONP to grab an HTML document. You need to wrap your HTML in a JavaScript variable. JSONP has some very specific requirements to make it work properly, including a callback function/attribute. If you're not in control of the server hosting the target page, you won't be able to make it work. This is a security precaution to prevent a random page from being able to steal your personal information from sites you're logged into via an AJAX call.
UPDATE
I read your question more thoroughly. It sounds like your problem is that you're in a development environment that doesn't have the resource in question. JSONP isn't the answer because it's a lot of trouble to get running just to make your page work in development. You should create a local copy of the target HTML and grab it using a relative or server-absolute URL such as "/the/page/i/need.html" instead of "http://myserver.com/the/page/i/need.html"
If you want to get the data by jsonp, then the server side need to support jsonp.
There is no way just change the dataType to get the data.
If the server side doesn't support jsonp, then you need to make a proxy in your localhost.
As the title says I'm attempting to retrieve a json from an api given by the site. I've tried a variety of things now and have gotten varied results. I want to be able to retrieve and parse the json to get the information that I want out of it. Here's what I've tried:
1) $.ajax()
Code chunk (runs when a button is clicked):
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
alert('Success!');
}
});
This produces a "Origin null is not allowed by Access-Control-Allow-Origin." error and does not get a response from the server (for Chrome or FF, I don't care about IE since this is a small project for my use). Looking around I thought the problem might be that I need it to be a jsonp dataType since I am trying to connect to an outside website. This lead me to try #2
2) $.ajax with jsonp dataType
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function(data) {
alert('Success!');
}
});
I also appended "&callback=?" to the end of "url" that I give to the function. Using Chrom's Dev Tool I can see a response from the server this time but the alert never displays. I used JSONLINT to confirm that the response was a proper json (it is) and I've tried setting the json to a variable so I can play with it (along the lines of initializing a variable earlier in the script tag [var response;] and trying to assign the json to it[response = data;]). This produced undefined when I tried to alert(response); later on (I don't believe the response=json; bit ever got called for some reason).
I've also tried using $.getJSON but looking at the api for it it apparently just runs $.ajax anyway (I luckily got the same responses/errors when trying json vs jsonp for $.getJSON as I did when trying $.ajax). When I try as a jsonp Chrome (FF doesn't produce this error) shows a "Unexpected Syntax Error: Unexpected token :". This makes me think that the site I'm trying to talk to doesn't have jsonp working and I can't access the third party site as just a json request. The link talks about how setting the server to return as application/json rather than text/html, like I get from my response, fixed the problem for them (but again, I'm trying to access a third party site and thus I can't access the server).
I've tried this in Chrome and FF and looked at Dev Tools/Firebug for each and seen the same thing (though FF doesn't produce the origin error, but that's apparently a bug with Chrome anyway).
Also: I've taken the json response returned and run $.parseJSON on it and been able to grab various pieces but how can I access the json once I get $.ajax/$.getJSON working?
Any thoughts/solutions would be greatly appreciated.
I once got the Unexpected Syntax Error: Unexpected token : error too.
It seems like the site doesn't support Cross-Domain-Loading.
What API are you trying to use?
More than likely the response is valid JSON, but not valid JSONP. The 3rd party server has to support JSONP for you to get a JSONP response. If you do not have control of the 3rd party server, your only real option is to use a server-side proxy or YQL.
Don't use JQuery AJAX for JSONP.
Use <script type='text/javascript' src=' URL_GOES_HERE&callback=BLAH '></script> which will surround the json object with a javascript method call, and you can then use the data from the 3rd party source.
http://en.wikipedia.org/wiki/JSONP
Try the JSONP plugin. It's one of the few plugins I recommend, only because it's light and does what it should. It also allows you to check for responses other than success. Works great for JSONP, and resolved an issue I had with using a subdomain and not getting proper error responses (which subsequently just halted the code).
Get it Here.
Did you tried this way ?
$.getJSON( url + "?callback=?", function(data) {
console.info(JSON.stringify(data, null, 2));
});
This is basically how I'm managing my JSONP callback to http://freegeoip.net/json/
jQuery.ajax(
{
url:'http://en.wikipedia.org/wiki/Football',
type:'get',
dataType:'jsonp',
success:function(data){alert(data);},
}
i want to read wikipedia page from my domain using jQuery, iam doing as above.
as expected wikipedia is sending data as pure html, but when we use $.ajax to get cross domain data it expects data received to be in json format so iam getting error and unable to read the wikiepedia response.
please suggest me how can i read wikipedia url using jquery/javascript (without involving any server side tech) also is there any api available through which i get json from wikipedia.
There is a Wikipedia API (more precisely, MediaWiki, the engine of Wikipedia, has an API). You can read more about it here: http://www.mediawiki.org/wiki/API
Here is a jQuery example on how to fetch the formatted content of the "Football" page:
$.getJSON("http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?", {page:"Football", prop:"text"}, function(data) {console.log(data);});
The endpoint has to be configured to serve jsonp which in this case it is not. It will not magically transform the normal html response type into jsonp for you. You will need to create a proxy on your server which will serve you the remote content for example if you are using php then check out this link.
You can use YQL for page fetching and get the JSONP response.
http://developer.yahoo.com/yql/console/#h=select%20*%20from%20html%20where%20url%3D%22http%3A//en.wikipedia.org/wiki/Football%22%0A