ajax response on another domain - javascript

I have specific scenario to work with, It will be interesting and helpful to many developers, I have js file and a php file, In js file i code AJAX, using http request that send parameters to php file and get a response.
Now I have 2 domains
on 1st Domain
I have Database, Store some html codes, Can create AJAX to get data from database to a Javascript file.
on 2nd Domain
I want to display HTML codes from the 1st domain database using Javascript or AJAX
Is there any way to do this kind of trick?

You could write a wrapper script on server side to make the call to the second domain and then you just call your script.

You need use CORS technology also look at jsonp
Wikipedia source:
Cross-origin resource sharing (CORS) is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain the resource originated from. In particular, JavaScript's AJAX calls can use the XMLHttpRequest mechanism. Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request. It is more useful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests.
Simple Example:
To initiate a cross-origin request, a browser sends the request with an Origin HTTP header. The value of this header is the domain that served the page. For example, suppose a page from http://www.example-social-network.com attempts to access a user's data in online-personal-calendar.com. If the user's browser implements CORS, the following request header would be sent to online-personal-calendar.com:
Origin: http://www.example-social-network.com
If online-personal-calendar.com allows the request, it sends an Access-Control-Allow-Origin (ACAO) header in its response. The value of the header indicates what origin sites are allowed. For example, a response to the previous request could contain the following:
Access-Control-Allow-Origin: http://www.example-social-network.com
If the server does not allow the cross-origin request, the browser will deliver an error to example-social-network.com page instead of the online-personal-calendar.com response.
To allow access from all domains, a server can send the following response header:
Access-Control-Allow-Origin: *
Browser support:
CORS is supported by all browsers based on the following layout engines:
Gecko 1.9.1 (Firefox 3.5, SeaMonkey 2.0, Camino 2.1) and above.
WebKit (Initial revision uncertain, Safari 4 and above, Google Chrome 3 and above, possibly earlier)
MSHTML/Trident 6.0 (Internet Explorer 10) has native support. MSHTML/Trident 4.0 & 5.0 (Internet Explorer 8 & 9) provide partial support via the XDomainRequest object.
Presto-based browsers (Opera) implement CORS as of Opera 12.00 and Opera Mobile 12, but not Opera Mini.
The following browsers are also noteworthy in their lack of CORS support:
1. Camino does not implement CORS in the 2.0.x release series because these versions are based on Gecko 1.9.0.
2. As of version 0.10.2, Arora exposes WebKit's CORS-related APIs, but attempted cross-origin requests will fail.

Related

Bypassing CORS issue in Chrome [duplicate]

This question already has answers here:
Disable same origin policy in Chrome
(35 answers)
Closed 1 year ago.
We are facing an issue where using Chrome request via XMLHTTPRequest is getting failed with below error:
Failed to load <server url>: No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin '<client domain>' is
therefore not allowed access.
This error is Chrome specific since we are not getting this issue in IE. Is there anyway to bypass this error in JavaScript.
Basically, for development purposes only, you can start the Chrome Browser in relaxed mode using the disable-web-security flag:
Here's how to do it on windows (Credit to https://alfilatov.com/posts/run-chrome-without-cors/)
Right click on desktop, add new shortcut
Add the target as "[PATH_TO_CHROME]\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
Click OK.
The directory in 'user-data-dir' must have read/write permissions for Chrome.
You will get a warning banner in Chrome notifying about reduces security, because that is actually what you have here. USE ONLY FOR TESTING.
Note: This answer builds on the link-only answer by Franco Fontana which was deleted because of link-only but the link actually helped me.
No, fortunately there is not.
The same-origin policy is an security concept implemented by browsers to prevent Javascript code from making requests against a different origin/domain than the one from which it was served. So enabling developers to bypass this from Javascript would be a bad thing.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.
Source: Cross-Origin Resource Sharing (CORS)
If you're in control of the API:
Add an Access-Control-Allow-Origin header containing the domain your requests are originating from.
If you're not in control of the API:
Ask the developer of the API to have your domain added to an Access-Control-Allow-Origin header.
EDIT:
Adding the correct header will not 'make the request an OPTIONS request while the server only accepts POST'.
The OPTIONS request is a preflight request to check to see if the CORS call can actually be made. If the preflight request has the correct header, the POST request will follow as you can see in the image below:
You can find all of the basic CORS information in the article Understanding CORS
Although its limited, can try to use CORS anywhere https://github.com/Rob--W/cors-anywhere or the chrome extension here that allows you to bypass CORS (make sure you turn this off when not testing as it will cause issues with requests from other websites)

How does CORS plugin / --disable-web-security work on browser?

I'm sure I'm not the only one who have used/uses CORS plugins for browsers or --disable-web-security flag while making API calls to external (or even internal) API endpoints. I used this plugin to make Google Maps related API calls. But within the same application, ParseSDK API calls needed no CORS or --disable-web-security flag.
My question is : Why are these endpoints acting differently and how does CORS plugin solve the problem (even though we don't have control over those APIs)?
Thanks in advance.
Well, what that plugin does is highly irresponsible; It actually disables the same origin policy, which enforces that a website on a specific origin can only make requests to that origin.
The same origin policy actually just prevents a website from reading the response of a GET/POST request, the request itself is made, because it's considered safe.
Over time this good security feature became a burden and people used workarounds like JSONP.
So we got a new, standardized way to access foreign origins:
CORS (Cross-Origin Resource Sharing) is a mechanism that allows a web server to specify that another origin is allowed to access its content. This is done with Access-Control-Allow-Origin: example.com which allows example.com to access the response even if the response is from a different origin.
The Access-Control-Allow-Credentials: true would also allow the credentials, which includes cookies and HTTP Basic authentication to be sent within the request.
You can also specify a wildcard for Access-Control-Allow-Origin: *, which allows all websites to access this response. However when you do this you have to specify Access-Control-Allow-Credentials: false, so no credentials are exposed.
This is the only correct way to implement a public accessible AJAX API in the internet.
However this plugin just simply disables the same origin policy completely which is extremely dangerous.
The link you posted (did you read the description?) specifies exactly what the extension does - it adds the Access-Control-Allow-Origin: * header to all responses. This is a CORS header that normally the server sends to notify the browser that you are allowed to make requests from arbitrary origins.
Parse SDK probably supports CORS on their server end.
Just for your information, when most people say CORS they are not referring to a browser extension. They're referring to the web standard called CORS. Documentation below.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

CORS in embedded javascript

I'm intending to add security for our Javascript code which gets embedded on other sites - eg: like analytics code.
The user copies 4-5 lines of the code and puts it on his site. The code actually downloads the real script as the next step.
I have been recommended to use CORS instead of the current JSONP calls as I can restrict the domains.
As I understand, the CORS would work only if the html page which will add my scripts needs to add access domains and if I add the access domains for the the js file, it wouldn't work.
Is the CORS for the final js or the html page intending to use my script?
Edit:
Since it's confusing to the users, I have made it more simple.
HTML in domain A adds my script from Domain B like Google analytics. Can I add access-domains: while rendering my JS or should the HTML add the access-domains in the response?
There is a good explanation from wiki for this question:
CORS can be used as a modern alternative to the JSONP pattern. While JSONP supports only the GET request method, CORS also supports other types of HTTP requests. Using CORS enables a web programmer to use regular XMLHttpRequest, which supports better error handling than JSONP. On the other hand, JSONP works on legacy browsers which predate CORS support. CORS is supported by most modern web browsers. Also, while JSONP can cause cross-site scripting (XSS) issues where the external site is compromised, CORS allows websites to manually parse responses to ensure security.
As I understand, the CORS would work only if the html page which will add my scripts needs to add access domains
You can access all domains via:
Access-Control-Allow-Origin: *
Also now CORS has good support.
P.S. IE8-9 has own imlementation by XDomainRequest.
CORS works by having your server output the Access-Control-Allow-Origin header containing the allowed domains. The sites that make ajax requests to your server don't need to do anything special to enable CORS, there is no configuration required. The sites just simply make normal XHR requests and the browser will internally handle the CORS.
You control the CORS access from the header on your server. In CORS, you can also control the HTTP verbs that are allowed, for example POST or GET (Access-Control-Allow-Methods) or the permitted request headers (Access-Control-Allow-Headers).
Note that IE8 doesn't support the CORS XHR, Microsoft decided to create their own CORS implementation with XDomainRequest. So if any of the sites that call your server want to support IE8, they will need to use XDomainRequest instead of XMLHttpRequest. There is no support for CORS in IE7 or eariler - not even XDomainRequest.

How can I make cross-domain requests with custom headers without using XDomainRequest or XMLHttpRequest?

I have a single page web application delivered from www.example.com. This web applications
needs to make AJAX requests against another server named api.example.com
it has to set certain header fields like Authorization when sending requests to api.example.com
it has to be compatible with recent and not so recent browsers (for example IE >= 8)
All this works by handling CORS requests on api.example.com with Chrome (and other recent WebKit-based browsers) using XMLHttpRequest. IE older than version 10 doesn't implement CORS for XMLHttpRequest and instead provides the non-standard XDomainRequest object for cross-domain requests. But XDomainRequest does not implement a way to set HTTP header fields.
So my question is: How can I make cross-domain requests with custom headers without using XDomainRequest or XMLHttpRequest? What is the best practice workaround?
Edit: I have control over all involved servers (*.example.com).
I'm afraid there is no other way but to implement a proxy for this request in your application's server side. An example.

JavaScript access from parent domain to subdomain?

I've read that setting document.domain = "example.com" lets me access the parent domain from a subdomain.
Will the same work the other way around?
Let's say my main site is running under http://example.com. All API functions that I want to access via AJAX (GET & POST) are hosted on http://api.example.com.
Will I be able to access api.example.com from example.com?
EDIT: Looking at document.domain again, I don't think that this will solve the problem. The result from calls to api.example.com are not necessary HTML, but output from a PHP script running on the API server. It can be JSON, plain text, etc. so there's no way to set document.domain for that (since it's not an iframe).
You need to set document.domain on BOTH pages
Alternatively set CORS headers on your server:
http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
A Quick Overview of CORS
Firefox 3.5 and Safari 4 implement the
CORS specification, using
XMLHttpRequest as an “API container”
that sends and receives the
appropriate headers on behalf of the
web developer, thus allowing
cross-site requests. IE8 implements
part of the CORS specification, using
XDomainRequest as a similar “API
container” for CORS, enabling simple
cross-site GET and POST requests.
Notably, these browsers send the
ORIGIN header, which provides the
scheme (http:// or https://) and the
domain of the page that is making the
cross-site request. Server developers
have to ensure that they send the
right headers back, notably the
Access-Control-Allow-Origin header for
the ORIGIN in question (or ” * ” for
all domains, if the resource is
public) .
The CORS standard works by adding new
HTTP headers that allow servers to
serve resources to permitted origin
domains. Browsers support these
headers and enforce the restrictions
they establish. Additionally, for HTTP
request methods that can cause
side-effects on user data (in
particular, for HTTP methods other
than GET, or for POST usage with
certain MIME types), the specification
mandates that browsers “preflight” the
request, soliciting supported methods
from the server with an HTTP OPTIONS
request header, and then, upon
“approval” from the server, sending
the actual request with the actual
HTTP request method. Servers can also
notify clients whether “credentials”
(including Cookies and HTTP
Authentication data) should be sent
with requests.

Categories