Cordova local ajax request error - javascript

I'm trying to retrieve informations from PHP script on localhost
app.js on Cordova application :
var url = 'http://localhost:8000/locations';
$.ajax({
url: url,
type: 'GET',
contentType: "application/json",
async: true,
dataType: 'jsonp',
crossDomain: true,
success: function(resp){
console.log(resp);
},
error: function(err) {}
});
and the php code (with Laravel framwork)
return Location::all()->toJson();
I have this error
Refused to load the script
'http://localhost:8000/locations?callback=jQuery21309354114597663283_1431278135791&_=1431278135792'
because it violates the following Content Security Policy directive:
"default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'".
Note that 'script-src' was not explicitly set, so 'default-src' is
used as a fallback.

You need to add policies to your Cordova app.
http://content-security-policy.com/
http://www.html5rocks.com/en/tutorials/security/content-security-policy/
Second link is exactly what you need, article is well written I can quote only:
https://apis.google.com/js/plusone.js in the context of this page’s
origin. We trust that code, but we can’t expect the browser to figure
out on it’s own that code from apis.google.com is awesome, while code
from apis.evil.example.com probably isn’t. The browser happily
downloads and executes any code a page requests, regardless of source.
Instead of blindly trusting everything that a server delivers, CSP
defines the Content-Security-Policy HTTP header that allows you to
create a whitelist of sources of trusted content, and instructs the
browser to only execute or render resources from those sources. Even
if an attacker can find a hole through which to inject script, the
script won’t match the whitelist, and therefore won’t be executed.

I just added this in the head tag
<access origin="*" />
and it works !

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource in simple html form

why this error is showing in my simple html form, I want to get xml data in my simple form to show news on my webpage, but this error is showing continuously, please help
$.ajax({
type: "GET",
url: "https://news.google.com/rss/search?q=Nigeria&hl=en-PK&gl=PK&ceid=PK:en",
dataType: "xml",
success: function(xml) {
console.log(xml)
}
});
It is up to the server that has the resource to allow cross origin access.
Probably there is API for what you are trying to do. API gets implemented by the resource owner and provides controlled access.
Or you can use RSS if there is one.
What you could potentially do is run your requests through a CORS proxy. For example:
$.ajax({
type: "GET",
url: "https://cors-anywhere.herokuapp.com/https://news.google.com/rss/search?q=Nigeria&hl=en-PK&gl=PK&ceid=PK:en",
dataType: "xml",
success: function(xml) {
console.log(xml)
}
});
You can see that this works by simply pasting this code snippet into the console.
This essentially bypasses the CORS issues for you. I would only recommend using this hosted version if you don't have a lot of traffic, otherwise you should host your own version of the CORS proxy.
This is because of CORS(Cross Origin Resource Sharing) policy implemented by browsers. Which means browsers doesn't allow certain requests to be sent from a domain to another domain. However this is not applicable to all type of requests.
Check this link to understand what all requests come under this policy
Inorder to make this work , the other server, in your case https://news.google.com, have to setup in such a way that it allows cross domain requests. This is achieved by servers telling the browser that it is ready to accept cross domain requests from your domain, by adding certain cors related headers. One such is Access-Control-Allow-Origin. But I am afraid you can't do it since you aren't the one managing this server.
Work-Around
Use your backend to send the request to google. So that your xhr request calls your server and your server calls google. No browser No Cors.
xhr---> yourdomain.com/news/get---> someotherdomain.com/news/get

how to pass a javascript code in jsonp format and execute

Can we use jsonp to overcome same domain policy of JS.
I need to run script from a domain x to run on domain y. So is it possible to send a script and execute ??
Yes, that is the entire point of JSONP.
There is no restriction on where you can load a script from (other then the usual http/https conflicts).
You can import a JS/CSS file from any other domain.
If you need to GET data from some other domain, you will need to get it through JSONP.
Please note that cross domain requests work only for HTTP/S GET and the only format of data accepted is JSONP.
e.g.
my code using jquery
$.ajax({
url: 'https://www.otherDomain.com',
type: "GET",
crossDomain: true,
data: parameters,
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
function localJsonpCallback(json) {
/* Do stuff */
}
The server side response needs to be in JSONP.

https request in chrome packaged app (java script)

I'm trying to send a request from chrome packaged app:
$.ajax({
url: "https://accounts.google.com/o/oauth2/auth?client_id=xxxapps.googleusercontent.com&response_type=id_token&scope=openid%20email", //"https://www.googleapis.com/plus/v1/people/me",
jsonp: "responseText",
dataType: "jsonp",
data: {
q: "select *",
format: "json"
},
success: function( response ) {
console.log( response );
}
});
and recieving the following error:
Refused to load the script
'https://accounts.google.com/o/oauth2/auth?client_id=xxx&q=select+*&format=json&_=xxx'
because it violates the following Content Security Policy directive:
"default-src 'self' chrome-extension-resource:". Note that
'script-src' was not explicitly set, so 'default-src' is used as a fallback.
The manifest file of the app contains following:
"content_security_policy": "script-src 'self' https://accounts.google.com; object-src 'self'"
How to fix this error?
The error messages you're seeing are the answer. The first one was saying you were violating CSP. The second is saying you can't change CSP in a Chrome App.
Read more about Content Security Policy in a Chrome App, and for completeness another discussion in the context of Chrome Extensions. You have the answer to the question you asked, but you might want to ask a new question explaining what you're trying to do (as opposed to why you're seeing these error messages). If your overall goal is to run external (i.e., downloaded) content in a Chrome App, the only way to do it according to the Chrome Web Store's developer terms of service is to sandbox the code and message to/from your normal, privileged code.
I think I've solved it by adding to manifest:
"permissions": ["https://accounts.google.com/"]

consuming PHP service returning valid json with $.ajax

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

Load cover-image with javascript on https website

Our app is delivered through https, we have a possibility of embedding vimeo videos in it.
Now, we're using JavaScript to load among other things a cover-image.
A call could look something like this
$.ajax({
type: 'GET',
url: 'https://www.vimeo.com/api/v2/video/80973511.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function(data) {
var thumbnail_src = data[0].thumbnail_large;
console.log(thumbnail_src)
}
});
Note that we're requesting over https here, and if you open the url above in a browser it'll load info about "The Work of Zina Nicole Lahr", over HTTPS.
Now, execute this on a site with jquery on https and you'll get the following message:
[blocked] The page at 'https:// ------------erased---------------' was loaded over HTTPS, but ran insecure content from 'http://vimeo.com/api/v2/video/80973511.json?callback=jQuery19106951870615594089_1386837009643&_=1386837009644': this content should also be loaded over HTTPS.
It's like the vimeo-api is redirecting the JSONP request to an insecure connection.
The network-tab says the same.
Something tells me https is not supported in these cases?
Hints:
https://vimeo.com/forums/topic:17127
Take out the www from your url. It looks like www.vimeo.com on either protocol redirects to http://vimeo.com.
https://www.vimeo.com/api/v2/video/80973511.json redirects
https://vimeo.com/api/v2/video/80973511.json does not redirect

Categories