Mootools Request Class and CORS
I am trying to use CORS to have a script make an Ajax request to geodata. My script calls this web service method: http://www.geonames.org/export/web-services.html#findNearby
If you check the fetch response headers, they include: Access-Control-Allow-Origin: *
When I try to do it with mootools (version 1.4.5 only):
var urlGeonames = "http://api.geonames.org/findNearbyPlaceName";
var req = new Request({
method: 'get',
url: urlGeonames,
data: {
'lat': '89.18',
'lng': '-0.37',
'username': 'myusername',
'radius': '5'
}
}).send();
then I get the error:
XMLHttpRequest cannot load
http://api.geonames.org/findNearbyPlaceName?lat=89.18&lng=-0.37&username=myusername&radius=5.
Origin http://127.0.0.1 is not allowed by Access-Control-Allow-Origin.</pre>
On the other hand, when I try to use the old style Ajax code like this:
invocation = new XMLHttpRequest();
if(invocation)
{
invocation.open('GET', urlFlickr, true);
invocation.onreadystatechange = handler;
invocation.send();
}
then it works and I get an XML response in XXR responseXML.
I found this post CORS POST request works with plain javascript, but why not jQuery? that looks like. But here I am not dealing with my server, so I can only work from the javascript side.
Has anyone worked with CORS and mootools and can help with this issue? thanks JM
source to share
Hey whose husband is checking mootools for more JSONP, this will solve your problem:
http://mootools.net/docs/more/Request/Request.JSONP
Also looks like you are forgetting to request it in JSON format from geonames.org
Try something like:
var myJSONP = new Request.JSONP({
url: 'http://api.geonames.org/findNearbyPlaceNameJSON',
data: {
'lat': '89.18',
'lng': '-0.37',
'username': 'myusername'
},
onRequest: function(url){
// a script tag is created with a src attribute equal to url
},
onComplete: function(data){
// the request was completed.
console.log(data);
}
}).send();
Hope this helps!
source to share
First answer on this thread: MooTools CORS request and native Javascript
May I help.
Basically the X-Requested-With header is automatically sent by Mootools with the request, but the server must either be configured to accept this header, or you can remove it with
delete foo.headers['X-Requested-With'];
Before calling
foo.send();
To allow this by the server, you can add this to your script's .htaccess file that returns JSON data:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
So yours looks like this:
var myJSON = new Request({
url: 'http://api.geonames.org/findNearbyPlaceNameJSON',
data: {
'lat': '89.18',
'lng': '-0.37',
'username': 'myusername'
},
onRequest: function(url){
// a script tag is created with a src attribute equal to url
},
onComplete: function(data){
// the request was completed.
console.log(data);
}
});
delete myJSON.headers['X-Requested-With'];
myJSON.send();
source to share