Calling RESTFUL service from JQuery - javascript

I am trying to call a resource from a server using REST, the Restful Service is on another server.
When i run the script below i get XMLHttpRequest cannot load file:///C:/xampp/htdocs/Rest_Client/application/views/www.creadevz.com/Restful_Server/index.php/api/Example/users/. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
<script>
document.write('Started');
jQuery.ajax({
type: "GET",
url: "www.creadevz.com/Restful_Server/index.php/api/Example/users/",
dataType: "json",
crossDomain: true,
success: function(html){
document.write('success');
document.write(html);
}
});
</script>
I have 2 Questions:
1- Why did it append file:///c:/xampp/htdocs/Rest_Client/application/views
2- how to over come the cross domain resource access restrictions.
Extra information:
1- I am using CodeIgniter with Philip Sturgeon's REST server.
2- I followed the Philip Sturgeon's tutorial and used the Example api supplied with the framework
3- I used hurl.it to test the api and it worked fine.
Solutions I have found:
1- CORS
2- JSONP
Most opinions online suggest CORS over JSONP but i am not sure how to implement it in an efficient way, also since hurl.it called the api perfectly there must be a way they are over coming the cross domain resource access restrictions without the CORS Headers.
Thanks in Advance for your help
Edit:
I failed to mention that this is done with the purpose of using it with Phonegap
In an attempt to use the CORS Headers efficiently i added it at the start of the response function in Rest_Controller.php

To answer you first question
please correct is url ,it shoud have "http://" now your code will look like this .
<script>
document.write('Started');
jQuery.ajax({
type: "GET",
url: "http://www.creadevz.com/Restful_Server/index.php/api/Example/users/",
dataType: "json",
crossDomain: true,
success: function(html){
document.write('success');
document.write(html);
}
});
</script>
This will now not append append file:///c:/xampp/htdocs/Rest_Client/application/views

It's simple, if you are working on chrome, you can install this plugin , it works for me. I hope that works for you.
Good luck

Related

Looking for clarification; How do I access a particular webservice with local files an Ajax

It could be I have completely misunderstood how web services work.
So there's a webservice I want to access through a javascript file sitting in a folder on my desktop. The server I am trying to access has not set a CORS header, so I have some trouble just using regular ol' ajax.
And frankly I am not sure where to go from here.
$.ajax({
type:"get",
crossdomain: "true",
url: "https://name", //actual name redacted from this question
success: function(data){
console.log(data);
}
});
A regular get like this will print the following in firefox's console.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ws.zooom.no/v1/channels. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
I got a hint from the task giver that I need to set the following in my "hosts file"
#127.0.0.1 www.domainname.com
Which confuses me. I have little to no experiences hosting anything, but does this hint that I need to maybe virtually host my "webpage" to access the webservice? It probably doesn't help to say I feel at a loss here.
So the bad news is that unless the 3rd party service either allows cross-domain requests (this is a configuration on that 3rd party server), or allows JSONP requests, you really have no option to access this service using a browser and javascript.
You could perhaps build your own service to proxy requests to that third party service. This would give you control over domain, CORS, JSONP, etc.
I found a solution.
Using something called "JSONP" that I had never heard of until now, i wrote a request like this
$.ajax({
type: 'GET',
url: "https://DOMAINNAME.com",
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data)
},
error: function(e) {
console.log(e.message);
}
});
This somehow completely negated the CORS problems

What to do when an API doesn't allow Access-Control-Allow-Origin

I'm driving crazy with all this same-origin-policy thing.
When I try to do a request to the Google Maps API I have no problems:
var jsonData = $.ajax({
url:"http://maps.googleapis.com/maps/api/geocode/json?address=",
dataType:"json",
async:true,
success: function(json){...}
}
I think that is because Google Maps API allow Access-Control-Allow-Origin. But when I try to use the openls.geog.uni-heidelberg.de API I get the cross-origin error:
var xmlData = $.ajax({
type: "GET",
url:"http://openls.geog.uni-heidelberg.de/route?"
//dataType:"jsonp xml",
dataType: "xml",
async:true,
crossDomain : true,
success: function(xml){...}
}
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
One think I dont understand is if the openls API doesn't allow cross-origin why can do a request directly from my browser just typing the url like:
http://openls.geog.uni-heidelberg.de/route?start=9.256506,49.240011&end=8.72083,49.7606&via=&lang=de&distunit=KM&routepref=Bicycle&weighting=Shortest&avoidAreas=&useTMC=false&noMotorways=false&noTollways=false&noUnpavedroads=false&noSteps=false&noFerries=false&instructions=false
But I can not do it using jquery. I have also tried the jsonp solution but it's not working with xml.
Some idea of what is going on?
i struggled for way too long with CORS issues caused by the interaction of two projects running locally (Angular App and Node.JS Webservices)
Behold the short easy workaround : Chrome's plugin AllowControlAllowOrigin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
Just switch the radio button from red to green, and no more blocked request, error or warning !
I hope it'll work with your API, Of course it isn't a permanently solution but that's a great way to avoid loosing time on those anoying recurrent issues.

cherrypy/jquery CORS trouble

I've got a simple python web server based on cherrypy. Its resources shall provide an API. THe server has the following code to provide CORS:
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == "__main__":
cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)
cherrypy.quickstart(PyCachedAdmin(), config={'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
the server is running on localhost:8080. Now I've got a HTML file, available on localhost (default port 80) which loads jquery 1.9. I open the browser console to try the $.ajax to execute any AJAX request to the cherrypy server. I've been trying:
$.ajax({
url:'http://localhost:8080/',
type: "POST",
dataType: "json",
data: {command:"version"}
}).done(function(){
console.log('hej');
});
and
$.ajax({
url:'http://localhost:8080/',
type: "POST",
crossDomain: true,
dataType: "jsonp",
data: {command:"version"}
}).done(function(){
console.log('hej');
});
and
$.support.cors = true
and nothing worked. I'm getting either XMLHttpRequest cannot load http://localhost:8080/. Origin http://localhost is not allowed by Access-Control-Allow-Origin. or GET http://localhost:8080/?callback=jQuery19102827550224028528_1382823727186&command=version&_=1382823727187 404 (Not Found) when using jsonp (it's mysterious that it sends GET instead of POST). There is a few similar questions around, I tried them and these are my results (that something is still wrong).
PS the server is perfectly ok, since all curl tests pass. Something is wrong with the cross-domain stuff.
Are you activating the CORS tool?. You can use the tool by decorating the calling methods or set it on the configuration.
Given that the implementation of PyCachedAdmin is no expressed on the question I might guess that probably you are not enabling the tool, to do so you just need to change the config dictionary and make something like this:
cherrypy.quickstart(PyCachedAdmin(),
config={
'/': {
'request.dispatch':
cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True}})
Or if the methods that you are using on PyCacheAdmin has already been decorated or using _cp_config that extra configuration is not required and this answers will not help you.

jQuery xml cross domain data parsing fail in ie8

I'm new to jQuery and would like to parse an xml document.
So far, I've been doing:
$.ajax({
url: xmlUrl,
type: 'GET',
dataType: 'xml',
crossDomain: true,
error: function(){
alert('Error loading XML document');
},
success: function(xml) {
}
});
However, I always get the error message in ie8.
Here is the xmlUrl address which I want to parse.
http://api.facebook.com/restserver.php?method=links.getStats&urls=MyUrl
With really no luck. Any ideas? Thanks.
I'm afraid IE 8 does not support Crss Origin requests, hence does not allow the cross-domain request (unless you do not setup the browser itself).
As the service you are trying to use does not use any client's data, you can setup a proxy - simple PHP script, that retrieves the url and output (via curl or file_get_contents if allow_url_fopen is enabled), and use ajax without the crossdomain.
I'd suggest using the Facebook JavaScript SDK (http://developers.facebook.com/docs/reference/javascript/), as it will take care of that issue for you. Also the method of using the restserver is deprecated, you can use the new SDK to call into the Graph API.

How to load a XML from a 3rd party site with Javascript/JQuery?

I am trying to load a 3rd party xml document using JQuery/Javascript, but without success:
alert("Before");
$.ajax({
type: "GET",
url: "www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml",
dataType: "xml",
success: function(xml) {
alert("OK");
}
});
alert("After");
The "OK" box is not displayed, but the xml is available with a browser. This code example is available at JSFiddle.
How is one supposed to load a 3rd party XML in Javascript?
The protocol has to be specified, http:// (or perhaps https://).
url: "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml",
Updated code: http://jsfiddle.net/gv9Kr/1/
As you can see, the code does not work, because of the Same-origin policy.
It is due to cross domain restrictions. There are plenty of resources available in the internet just google on it. There are various work arounds to it one of which is YQL
same origin policy prevents you from doing that. you must find ways to circumvent this. for JSON type data, there is JSONP. here's a question from SO that might be related to your issue.

Categories

Resources