I have a JSP page and I want to make a jQuery AJAX call to a PHP server on a different domain. Is this possible? What kind of errors might I run into?
-
Have you tried? if so, what did you find? – Ohgodwhy Jan 08 '14 at 01:16
-
I have tried but the error is occurring at the clients end and I cannot get them to run an error report :/ – Nick Chapman Jan 08 '14 at 01:29
3 Answers
It is possible, but it's kind of tricky. To overcome cross domain issues, you need to use JSONP technique instead of the usual AJAX we mostly use.
The main idea of JSONP, is to create a tag dynamically in the HTML document, sending a callback function name to the requested server. The server will then invoke the callback with the returned data by returning a valid Javascript script. Note that you can only make GET request, don't bother with POST.

- 2,275
- 2
- 18
- 27
-
See http://stackoverflow.com/questions/2558977/ajax-cross-domain-call. Also, language is all but irrelevant in AJAX calls; as long as you return something you know how to read, implementation is a formality. – citelao Jan 08 '14 at 01:19
jsonp is a possible solution; another would be to create an API / web service on your PHP server that will return some json or xml, and call that from your java code. That way your ajax / client-side code could hit an endpoint within your application / domain, and you could use whatever java http libraries are available to post to your php script and get a response.
Using the web service approach is convenient, in case you end up wanting to retrieve the same data from different applications in the future.

- 3,358
- 1
- 21
- 27
If you control the other domain you can have it emit a CORS (Cross-Origin-Resource-Sharing) policy; which sounds scarier than it is. This will allow you to make cross domain AJAX requests.
Here's a guide on how to set it up: http://fritsvancampen.wordpress.com/2013/02/03/cross-site-origin-requests-aka-cross-origin-resource-sharing/
If you don't control the domain and there is no JSONp API available you'll have to use the proxy as linked by citelao which comes with it's own caveats.

- 57,230
- 10
- 89
- 128