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.
Related
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 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.
I am trying to get the contents of http://en.wikipedia.org through an ajax call. For this, I am using jQuery. Here is the code:
jQuery.ajax({
url:"http://en.wikipedia.org",
crossDomain: true,
dataType: "jsonp",
jsonpCallback: "myCallback"
});
function myCallBack(data){
console.log("ok");
}
The problem is that I get in Firebug this error:
SyntaxError: syntax error
<!DOCTYPE html>
So I would say that the html content is fetched, although the callback function is not run. At some point it encounters the specified tag, throws this error and stops running the script.
Do you have any idea where the problem might lie?
Is there any other way to get the contents of a html page? I do not want to use iframes, because that means I will not be able to use or modify its contents.
Its because you're Ajax function expects a json response from the provided url and it gives an html response, thats the reason you are getting a syntax error, the same error you will get from the Chrome debugger as well.
Updated:
What you're trying to do is called a Cross-Domain Request.
"For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed."
Reference
Solution:
You can resolve this issue by having a backend script which will the external pages for you. Like a proxy server, which resides the same domain, so you wont have to face the Cross domain issues.
And you can load them, by
$.get(url, success: function(data) { // the url that will fetch the external html page for you, located on the same domain
console.log("ok");
});
Your issue your having here is that you are calling across domains. Allthough you seem to have realised this and are using jsonp for your request, the document you are trying to pull ie wikepedia is not a jsonp document. So as soon as the ajax finds the html tags it will throw an arror, as you have defined that you are expecting a jsonp response.
You cannot just pull other websites data across domain with javascript due to the cross domain issues, if you want to accomplish what you are doing here you will need to use a back end language to get the data.
Usefull link is http://json-p.org/
Hope that helps
I'm trying to validate a feed, using the web service that is in this question.
But browser does not allow me to send a ajax GET request to another server. And there is a one second restriction per each request in that web service, so I can't mirror requests from my server.
This is my current jQuery code:
var reqUrl = "http://validator.w3.org/feed/check.cgi?url=" + encodeURIComponent(theUrl);
$.get(reqUrl, function(data) {
// do something
});
Isn't there any other way?
Ajax calls are not valid across different domains unless you use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also as noted by Luis in the comments, JSONP has to also be implemented on the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
I searched google and found this. the third answer says that:
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.(source)
you'd better see the answers of this question.
I think you can't use JSONP because you haven't any access to W3C script.
Update (explanations)
I the question I linked to there is another way that I can explain it to you. if you set Access-Control-Allow-Origin header to * as the answer said you can send requests to another domains. and to use it easily in an MVC application you can see this solution. Good luck
Update2
to allow just http://validator.w3.org/ you just should set Access-Control-Allow-Origin to http://validator.w3.org/
for more details as answer said go here.
As said you can use JSONP but the endpoint must also implement it, And its only used if you are requesting json data from the call. It looks like you are retrieving html.
You can also implement a simple proxy in your domain that pulls the data from the external location and serves it to the ajax call. You can develop a simple proxy in php using for instance CURL.
Make sure you understand the implications of this security wise making sure for instance that you protect your proxy to only make calls to that external url (whitelisting).
Update: I just noticed you cannot use the proxy solution. And after following the link you have suggested I have came across CORS, which I didnt event know about. So apparentry you can set some headers when you are serving the pages in your domain that will instruct the browser that requests to some domains can be done.
Check this page for how to implement it:
http://enable-cors.org/
I have read that you might have to tweak it a bit to work with IE but it seems that all browsers are now implementing it.
I know this is an old question, but I myself have been trying to create AJAX requests to validator.w3.org as well, hit the exact same issues and stumbled on this SO question.
However, I did find a solution;
As people have already stated, the main problem here is that the server must issue valid CORS headers, i.e.
Access-Control-Allow-Origin: *
I used Fiddler to check the response headers from validator.w3.org and sure enough, the headers were not set. However, they also have another tool that does at validator.w3.org/nu/.
Here is an example: http://codepen.io/DDN-Shep/pen/ogdGgO/
$('form').on('submit', function(e) {
e.preventDefault();
var data = new FormData(this);
$.ajax({
url: 'http://validator.w3.org/nu/', // Trailing '/' is important or you get a 301 HTTP response status code
type: 'POST',
data: data,
processData: false, // Required for jQuery & FormData
contentType: false, // Set by FormData, required by the server
success: function(data, status, xhr) { /* TODO */ },
error: function(xhr, status, error) { /* TODO */ },
complete: function(xhr, status) { /* TODO */ }
});
});
If you are ever unsure whether or not a server allows CORS, you can use this very helpful online tool;
test-cors.org = http://client.cors-api.appspot.com/client
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/