Bhushan
Bhushan

Reputation: 6181

Call URL from another server using jQuery post

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", "*");

Upvotes: 0

Views: 1189

Answers (3)

danasilver
danasilver

Reputation: 556

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.

Upvotes: 2

Talha Masood
Talha Masood

Reputation: 993

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.

Upvotes: 1

MarkHoward02
MarkHoward02

Reputation: 154

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.

Upvotes: 1

Related Questions