Call URL from another server using jQuery post - javascript

I am using jQuery.post() method to send request to another server and get response from that server.
$.post('http://www.example.com:9876/example/myServletURL',{param1:param1}).done(function(data)
{
alert(data);
});
But I am not getting any response from the server. I have checked on server I am getting the request sent by post method.
If change the URL to Servlet which is in same war file(same domain) I am getting the response.
I have searched and found that this might be because of same origin policy.
My question is that how should I allow cross domain request using jQuery.post() method.
EDIT1
Domain is the same one, but the port numbers are different, for two different servers used for deployement.(Apache web server for php and Glassfish for java)
Solution
I have put following code to allow cross domain requests in my servlet.
response.addHeader("Access-Control-Allow-Origin", "*");

You can't change the cross domain request policy in the request, as that would defeat the security purpose of the same origin policy. CORS (Cross Origin Resource Sharing) has to be enabled on the server that sends the response. The response header must contain 'Access-Control-Allow-Origin': '*'. * allows any site to access the server and can be substituted with a single site if you don't want to give access to everyone. If you have control over the server to which you are posting, http://enable-cors.org/index.html is a great resource on how to enable CORS for your request/response.

What I did in a past project was Posted the data to an ASPX page on my own server from jQuery which then Posted the data to the true destination server. This page also Responded back the Response from the destination server.
I called the page PostData.aspx and sent the destination url as an escaped querystring parameter which kept it soft enough to use on other projects.

You can actually allow Cross Domain Requests on your server but be very careful because this is not very security friendly way.
I did this with PHP where you can allow cross domain by sending some headers in the request. You can do the same in PHP.
May be this link can help you => CrossDomain ajax request using CORS
If not let me know in comments.

Related

Does "Access-Control-Allow-Origin" help me against if someone points their domain to my server?

Maybe I misunderstood how to fully implement CORS in my server.
Given this screenshot of a request done via Chrome.
We can see that the we are visiting the site shakh.photography, the request URL is a POST ajax request towards /api/get-videos/ but the response contains a Access-Control-Allow-Origin header that mentions a totally different domain.
Even though the webserver respons with a Access-Control-Allow-Origin header, it is ignored by the browser. Everything still works.
I thought only setting the Access-Control-Allow-Origin was sufficient to only allow requests coming from the specified origin.
What have I missed?
Until it's fixed, this situation is testable by visiting shakh.photography.
The request is going to same-origin i.e. shakh.photography/api/.. hence no OPTIONS preflight being sent.
If the request were send from some third party's webpage say third.party then browser would send OPTIONS and server would check for its origin policy and return error as only gamezelle.com is allowed as of now.
If it were sent from gamezelle.com the response would be OK and then browser would send subsequent request.
The Same Origin Policy only stops a site from reading a cross origin Ajax response. This protects against a user's cookies being used by an attacking site to take data from your site using the authority of the user.
CORS allows you to selectively weaken the Same Origin Policy, it isn't used to strengthen it.
We can see that the we are visiting the site shakh.photography, the
request URL is a POST ajax request towards /api/get-videos/ but the
response contains a Access-Control-Allow-Origin header that mentions a
totally different domain.
Even though the webserver respons with a Access-Control-Allow-Origin
header, it is ignored by the browser. Everything still works.
Yes. This is normal. The request is from Site A to Site A. None of the cookies or other credentials the user might have to Site B are available to the Site A (the browser sandboxes them from each other). You simply have a server which responds to both URLs with the same data.
A third party could do that, but they couldn't do it for just your API (except via a proxy, which is a different issue, with even fewer security implications). They'd have to make the whole site available under the other hostname, this shouldn't cause any security worries.
If you don't want that, then configure your server so that it uses Virtual Name Hosting and delivers different sets of content based on the Host header in the request.

Get data from other domain by get method

I am trying to implement religious calendar for my client's website. I have service that gets xml/json data of calendar that is on another domain. Link works, but when I try get it from jQuery get method it success but there is no data
$( document ).ready(function() {
$.get('http://api.xhanch.com/islamic-get-prayer-time.php?lng=16.047624400000018&lat=45.78988090000001&yy=2014&mm=11&gmt=1&m=xml', function(data) {
alert(data);
});
});
For now, request is only from localhost but, I thing, it is not matter. So, is there an error or there is another way to get this data? I tried jQuery.ajax() but it is the same. The request succeeds but there is no data to alert.
Web browsers block AJAX requests to different domains due to security reasons unless "Access-Control-Allow-Origin" headers are set in the response from the server. When an AJAX request is coming from users, web browsers checks if the target domain is same or not. If the target domain is the same, the request is sent. Otherwise the browser sends a different request to the remote server and checks the corresponding response for the headers. If the headers contains the permission for cross domain requests, the browser sends the user's AJAX request to the remote server. Otherwise browser blocks it... The server you are sending the request seems not to be setting the headers and because of that the browsers don't allow.
As an alternative you can create a proxy at your server side. The request from the users will be sent to your server with the same domain. Then your server will send the request to the remote server (api.xhanch.com) and get the response. Then you can reply the user's response with the response you got from the remote server.
Also there are some methods to relax the same origin policy (Eg: JSONP). You may google and learn them..

is it possible to ignore ajax cookies via javascript

Is there a programmatic way in javascript to ignore cookies sent from the server (without changing browser settings).
We use certain plugins on our web server that will randomly update our security cookie. However this causes issues for some of our URLs and we want to ignore those cookies for some cases.
Our security architect recommended we look into this possibility.
example:
1). create ajax request with URL: www.site.com/abc/comtd
2). ignore any cookies that come back in the response
The only way I can think of is to send the AJAX request from a completely different domain. Because the AJAX would be a Cross-Origin Resource Sharing (CORS) request, any response headers would be denied unless the server sends the access-control-allow-origin header. If the AJAX request is not a CORS request, the browser has to respect all Set-cookie headers it receives per the standard.
its not an option in our case to change domains. We need to pass cookies to the server or the requests will not get through security. If we change domains our security cookies would not get passed. What we want is to pass the cookies but ignore any set-cookie response headers for certain URLs.
I think this is not possible on the browser so I am investigating some Apache server plugins like mod_headers. Maybe we can do it on the server itself. Im closing this question and will open another one related to mod_headers.
Just a thought - if you send the request from a WebWorker - I think that is isolated from the main browser context ?

Javascript HTTP GET and POST

When initiating a HTTP GET or POST request:
Common browsers do not allow Javacript to call cross domain
So it means that every HTTP request from a given domain the "Host" in the Request header represents the origin host, say foo.com and that it cannot be modified by the client request?
Furthermore, when a request originated from a subdomain, like bar.foo.com then the "Host" in the request header will be "bar.foo.com"
And that this holds true when doing Cross-domain HTTP request, i.e. the "Host" will be foo.com or if from subdomain bar.foo.com, and that the receiving end (the other domain) will see the "Host" as these hosts respectively?
Everything through the HTTP browser sandbox (not just AJAX calls! IFRAMEs have restrictions based on the same conditions, for different things - namely, you can't control the content of an IFRAME on another domain/host/port/proto, just load pages and see the URI of what is loaded. Content in JS is off-limits) is done client-side rather than server-side: your browser will actively refuse to query anything that does not have:
The same hostname (subdomains count as different hostnames)
The same port
The same access method (HTTP or HTTPS)
For AJAX, this leads into a big red "cannot get due to security"-esque error. For some browsers, the request does happen: there is a way to bypass this restriction, using access-control headers. These effectively tell your browser "I'm friendly to x", where x is a wildcard list of domains (and where * means everything).
To figure this one out, browsers will perform the request, and if CORS is not on, will actively fire an exception (XMLHttpRequest: x is not allowed by y). The request, however, has happened.
The obvious solution is to add an Access-Control-Allow-Origin header in order to signify that cross-domain queries to this site are okay. However, bear in mind two things:
Most browsers have it, but some don't (IE8 <.<)
CORS has some little bugs of its own if the URLs are hardcoded in the script (read up on it!)
You'll therefore want a JSONP fallback for IE. However, keep in mind that all this is done client-side and is no guarantee that there aren't any browsers that will actively disregard CORS or the webkit security model. The entire model also relies on client-side Host resolution.
If the question is "Is this true", then then the answer is no.
Browsers do allow JavaScript to create GET and POST requests cross domain. What they don't allow is javascript to read the response from a cross domain request.
The 'Host' in the HTTP header represents the host that the request is being sent to, not the website that caused the host. HOST is necessary because servers are often shared and one server may host many separate websites, so they need to know which one is being requested.
The website that created the website is often (although not always) identified in the 'REFERER' HTTP Header.
A server that supports CORS will inspect the Origin header in the request. The value will be as you described, the server that the request orignates from. In it's reply, the server will send a header called Access-Control-Allow-Origin. If this matches Origin, the browser will accept the response. It obviously also require the browser to support CORS.
Wikipedia have a fairly good explanation of how it works.
The Host HTTP request header is always the domain that the request is going to.
If you're initiating an HTTP GET or POST request using the XMLHTTPRequest method, then it won't let you send the request if the JavaScript code that sends it isn't on the same domain as the URL you're sending a request too - unless the browser supports cross-origin resource sharing.
If the browser does support cross-origin resource sharing (CORS), then it will send your request to other domains, but with an additional Origin header, indicating the site that served the JavaScript making the request. If the server allows the request, it'll respond with an Access-Control-Allow-Origin header, listing the domains it'll accept requests from.

Send post to a different domain using JS

I'd like a post request to be sent once a certain text input field is changed, using javascript.
So here is my current code:
<input name="message" onchange="$.ajax({type: \"POST\", url: \"http://example.com/example.php\", data: \"message=\" + document.getElementsByName(\"message\")[0].value});" />
Now, it's working on a regular connection, but it's not working on a secured connection (SSL).
I mean, the page is secured, but the request is sent to a non secured page.
Is there a solution?
Set the target attribute of the form to point to a hidden iframe.
You won't be able to read the response, but you can make the request.
If you want to read the response, you will need to proxy the request through your own server.
As David points out, t is not possible to do an asynchronous POST to a service on another domain, due to the (quite sensible) limitation of the same origin policy. JSON-P only works because you're allowed to insert tags into the DOM, and they can point anywhere.
YOu can do cross-domain AJAX w/ GET using JSONP: JSONP CrossDomain
It also covers how to do JSONP w/ jQuery
same origin policy prevents a document or script loaded from one origin from getting or setting properties of a document from another origin. Two pages are considered to have the same origin if the protocol, port, and host are the same for both pages. http://rj3.net/mdc/sop
make sure you specify ssl in the ajax url, when the rest of your page uses ssl too e.g https
You can't send it from a https to a http site. any https asset (html or otherwise) can only be accessed by something on the same domain / ssl certificate. so, you won't be able to do what you are trying to do (https to http). so since your page is served on https the targeted http site can not access it due to the policy

Categories

Resources