I need to send an AJAX request to, for example, port 8080 where a daemon is running there.
jQuery ajax() Method. The jQuery ajax() method provides core functionality of Ajax in jQuery. It sends asynchronous HTTP requests to the server.
Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url. Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.
jQuery ajax() Method The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method.
Browser does not allow cross domain AJAX requests due to security issues. Cross-domain requests are allowed only if the server specifies same origin security policy. To enable CORS, You need to specify below HTTP headers in the server.
This breaks the Same origin policy. You cannot use a different port, even when using the same domain.
You can use JSONP as Doug suggested.
Or else, as another possible workaround, you could set up a very simple reverse proxy (using mod_proxy if you are on Apache). This would allow you to use relative paths in your AJAX request, while the HTTP server would be acting as a proxy to any "remote" location.
The fundamental configuration directive to set up a reverse proxy in mod_proxy is the ProxyPass. You would typically use it as follows:
ProxyPass /ajax/ http://www.localhost:8080/
In this case, you would request /ajax/test.xml
with jQuery, but in fact the server would serve this by acting as a proxy to http://www.localhost:8080/test.xml
internally.
If you are using IIS, you may want to use the Managed Fusion URL Rewriter and Reverse Proxy to set up a reverse proxy.
You cannot POST
information cross domain, subdomain, or port number. You can however use JSONP if you have access to both the daemon and the requesting site. If data needs to be returned, then the daemon
needs to support a callback
query parameter and return it properly formatted.
Pass the information to the daemon:
$.getJSON('http://domain.com:8080/url/here?callback=?', { key: 'value', otherKey: 'otherValue' }, function(data){ // Handles the callback when the data returns });
Now just make sure your daemon handles the callback
parameter. For instance, if callback=mycallback
the return from the daemon (the only thing written to the page) should look like this:
For an key/value pairs:
mycallback( {'returnkey':'returnvalue', 'other':'data' });
For an array:
mycallback( [1,2,3] );
If you do not have a JSONP or similar mechanism in place, you cannot communicate cross domain using jQuery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With