We try to put some data to our server, the serverside should be okay because we tested already with DEV HTTP CLIENT Chrome extension. This is our code, I think it should work but I don't know how I could fix the cross domain error.
$.ajax({
type: "PUT",
url: '...../add?callback=JSONPCallback',
contentType: "application/jsonp; charset=utf-8",
data: JSON.stringify({
"name": "Test",
}),
jsonpCallback: "JSONPCallback",
crossDomain: true,
success: function (result) {
console.log('Success!');
},
error: function (a, b, c) {
console.error(a + " " + b + " " + c);
},
fail: function (e) {
alert('fail');
}
});
}
In the GET requests we used 'dataType: 'jsonp' ', but this is not working for PUT . Is there any possibility to PUT a json object and GET a jsonp object back in the success method?
JSONP is a GET operation (specifically, one created via a script tag).
You can do cross-domain PUT, just not in the JSONP way. Your target server has to allow your origin via Cross Origin Resource Sharing (and your browser has to support CORS with XMLHttpRequest, not the IE8 and IE9 XDomainRequest object — although if you need IE8 and IE9 support, if you look around you can find a plugin for jQuery that makes jQuery use XDomainRequest on those browsers).
If you are using modern browser (i.e. Firefox and chrome, safari), you can use HTML5 API CORS for doing this.
Here is the link for Using cors
Related
I'm trying to fecth data from a REST webservice into a HTML page. The problem is Internet Explorer 6 (which is my target station on XP SP3) that I'm struggling to make work.
Here's the code used :
$.ajax({
type: "GET",
contentType:"application/json; charset=utf-8",
dataType : 'json',
url: "https://jsonplaceholder.typicode.com/posts/1",
success: function(data) {
alert(data);
},
complete: function(xhr) {
alert(xhr.status+" "+xhr.responseText);
}
});
Tested on Firefox 52 ESR : both success and complete functions works.
On Chrome 49 : success works, complete is called but xhr.status is 0 and xhr.responseText is empty.
On IE6 success is not called at all and complete is called but xhr.status is 0 and xhr.responseText is undefined.
Tried what was already answered here on SOF like removing extra commas, adding dataType ... but still no success with IE6.
How can we do it once for all ?
Thanks
IE6 is ancient, it does not support CORS (not even with XDomainRequest).
There is no way to perform cross-origin RESTful HTTP requests with JavaScript in IE6.
If you want to perform a cross-origin request, then you will need to use some other (non-RESTful) approach such as JSONP.
As Quentin said, sending CORS request is not supported in IE 6/7, you could check this blog.
You could refer to the following code to use JSONP.
// Using JSONP
$.ajax({
url: "<request url>",
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
data: {
q: "select title,abstract,url from search.news where query=\"cat\"",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
Besides, please check this article:
Internet Explorer 9 and earlier ignores Access-Control-Allow headers and by default prohibits cross-origin requests for Internet Zone. To enable cross-origin access go to Tools->Internet Options->Security tab, click on “Custom Level” button. Find the Miscellaneous -> Access data sources across domains setting and select “Enable” option.
I want to read rss(xml) file but without using google rss feed.
i have try jsonp but it download the file and it throw a error "Uncaught SyntaxError: Unexpected token < "
$.ajax({
type: "GET",
url:'https://news.google.com/?output=rss',
//url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: "xml",
contentType: "text/xml; charset=utf-8",
headers: { "Access-Control-Allow-Origin":"*",},
success: function(xml) {
alert("success");
}
});
plz guys help me..
$.getJSON("//ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?", {
num: 10,
q: url
}).done(function (data) {
console.log(data);
});
Notes:
You're overdoing it. Don't try to specify information on the client side that the server actually has to supply (content type, allow origin headers, data type).
You don't want XML, you want JSON.
The name for cross-origin JSON requests is JSONP.
jQuery implements that for you if you use the getJSON() API method. You don't have to do anything besides adding "callback=?" to the URL.
Use jQuery Deferred callbacks (then, done, fail and always). They allow your code to become a lot more flexible.
Have a look at the documentation, too. https://developers.google.com/feed/v1/jsondevguide
You basically can't implement a web client RSS reader because you can't be sure that content providers will set the correct CORS header for their feed(s) ; My advice would be to not waste your time reading through endless CORS/JSONP lectures (and trying misleading code) but implement a server solution (like, say Pétrolette) and move on.
I want to call the following web service
var url = 'search.php',
data = {
addressdetails: 1,
format: 'json',
osmtype: 'node',
q: 'london'
};
$.ajax('//open.mapquestapi.com/nominatim/v1/' + url, {
type: 'GET',
data: data,
contentType: 'application/json',
success: function (data, status) {
var results = [];
if (status === 'success' && !data.error) {
console.log('success');
}
},
error: function(jqXHR, textStatus, errorThrown ) {
console.log('error');
}
});
I created a JSFiddle with this example: http://jsfiddle.net/JX27m/1
I've been told that IE8+ supports Cross-Origin Resource Sharing (CORS), so there should be a way to tweak this code to make it work on IE9, right?
Cheers,
Christophe
Check CanIUse.com and you will see IE 8 & 9 have partial support. My guess is because CORS was not actually introduced as CORS in the specification till 2009 (after IE 8 & too late to appear in IE 9). They probably implemented support of Access Control for Cross-Site Requests That eventually became CORS. They seem to support the XDomainRequest Object for cross domain requests. Check the Can I Use resources tab to find some other articles.
Assuming the server in question supports CORS and allows your origin, you can use IE's XDomainRequest object rather than XMLHttpRequest. jQuery doesn't do that for you because the jQuery team feel there are too many problems with the XDR object (details in this ticket, near the bottom), but you can do it yourself, or there are plugins for jQuery that provide that functionality. For instance, this one is linked from that same jQuery ticket.
I have the following code
function exista(word) {
alert(word);
var exists = 1;
jQuery.ajax({
async: false,
url: "http://api.wordreference.com/0.8/key/json/roen/" + word,
dataType: 'json',
method: "GET",
success: function(transport) {
if (transport.Error || transport.Response)
exists = 0;
}
});
return exists;
}
which verifies if a word exists or not in a dictionary. Problem is it gives an Access-Control-Allow-Origin error. From what I gathered it seems I must use JSONP but I can't really figure out how (sorry, I am just beginning to learn JavaScript and all that). So, got any idea on how to modify the above code?
Thank you.
Your dataType should be jsonp, not 'json`.
UPDATE
According to http://www.wordreference.com/docs/api.aspx:
Additionally, for JSPONp, the JSON API can take an optional callback
function in the query string; simply add "?callback={yourCallback}" to
the end of the URL.
so the API does support JSONP.
Additionally, JSONP means "JSON with padding", so you will get a JSON response. JSONP merely allows use of CORS.
By changing your dataType to jsonp:
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
You can override the default callback by specifying one with the jsonpCallback setting.
Finally, you should also add an error handler and set async to true:
jQuery.ajax({
"async": true, //cannot be false for JSONP
"url": "http://api.wordreference.com/0.8/key/json/roen/" + word,
"dataType": 'jsonp',
"method": "GET",
"error": function (jqXHR, textStatus, errorThrown) {
//included so you can see any errors
console.log(textStatus + ': ' + errorThrown);
},
"success": function (data, textStatus, jqXHR) {
//According to API documentation
//data will not likely contain either Error, or Response
//so, exists will likely not change to 0
if (data.Error || data.Response) {
exists = 0;
}
}
});
UPDATE:
The solution to both the error and the "need to be synchronous" is going to be what Pointy pointed out earlier. You'll have to create a server-side proxy that runs on the same domain as your script.
The server-side proxy can return JSONP, but frankly simply returning JSON or XML is simpler since CORS is not an issue, and the proxy can be synchronous. For a PHP example script, the Yahoo! Developer Network hosts source code for a simple proxy.
For anything else regarding a server-side web service proxy, you'd need to specify which server language you're using (and it would probably be better suited as a different question).
For JSONP to work, you not only have to code for it on your side, but the site you're targeting has to expect to be used that way as well, and respond to requests accordingly.
If the other site does not have a JSONP API already, and you have no control over it, then JSONP is not an answer. You'll have to create a server-side proxy of your own.
edit — according to the site, they do support JSONP. You just need to add "?callback=?" to the end of the URL.
My WordPress application is hosted on url http://127.0.0.1/wordpress/ and i added following script in WordPress header to get some token but it does not give any token
I copied that url ( http://127.0.0.1:8090/sample/sample/getToken ) and open in new tab it successfully return token but when i called it using $.ajax it does not return me token
<script>
$().ready(function(){
$("#signIn").click(function(){
alert("Display Alert Properly");
$.ajax({
type: "POST",
url: "http://127.0.0.1:8090/sample/sample/getToken",
contentType: "text/html",
success: function(token) {
window.open("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token, "_self", ""); });
});
});
You cannot directly access external resources via Javascript due to the Same Origin Policy implemented in modern browsers. However, there are a couple of solutions.
If the remote site offers JSONP you can utilize it to load external resources, but if they don't, you will not be able to access those resources directly.
If the remote endpoint does not offer JSONP, you will need a proxy script on your own server which accepts an AJAX request, makes the request to the external endpoint, and relays the response to your Javascript app. Be sure to secure such a script well to only accept requests to blessed endpoints, or you will have a nasty security hole to contend with.
Ajax is subject to the same origin security policy.
You can read about it here: http://en.wikipedia.org/wiki/Same_origin_policy
There are workarounds for this, including JSONP
Try this and see what error you get , it will help you see the actual problem
$().ready(function(){
$("#signIn").click(function(){
alert("Display Alert Properly");
$.ajax({
type: "POST",
url: "http://127.0.0.1:8090/sample/sample/getToken",
contentType: "text/html",
success: function(token) {
window.open("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token, "_self", "");
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
May be this will help.
You need to trigger JSONP behavior with $.getJSON() by adding &callback=? on the querystring, like this:
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?",
function(data) {
doSomethingWith(data);
});
Reference Ben Everard's answer