Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use XMLHttpRequest on a different port from a script file loaded from that port?

I have website that use XMLHttpRequest (jQuery, actually). I also have another site running on the same server, which serves a script file that makes XHR requests back to THAT site, ie.

http://mysite:50000/index.html includes

<script src="http://mysite:9000/otherscript.js"></script>

and http://mysite:9000/otherscript.js includes

$.ajax({
    url: 'http://mysite:9000/ajax/stuff'
});

The problem is - this doesn't work. The AJAX requests from the loaded script simply fail with no error message. From what I've been able to find this is the old same origin policy. Given that I control both sites, is there anything I can do to make this work? The "document.domain" trick doesn't seem to do a thing for XMLHttpRequest.

like image 807
EMP Avatar asked Nov 19 '09 23:11

EMP


People also ask

What can I use instead of XMLHttpRequest?

The Fetch API is a modern alternative to XMLHttpRequest . The generic Headers, Request, and Response interfaces provide consistency while Promises permit easier chaining and async/await without callbacks.

Is XMLHttpRequest same as AJAX?

XMLHttpRequest is the raw browser object that jQuery wraps into a more usable and simplified form and cross browser consistent functionality. jQuery. ajax is a general Ajax requester in jQuery that can do any type and content requests.

Where is XMLHttpRequest used?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

How can request content type be set to XML via XMLHttpRequest?

setRequestHeader('Content-Type', 'application/json') ; is added 1 line above or below the Accept header, the method used changes to OPTIONS, the Accept header changes to "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" and the Content-Type header disappears as if it wasn't seen.


1 Answers

I just solved a similar issue with a PHP service I'm currently playing around with (not sure how relevant a PHP solution is to this directly, but...) by making a single line proxy PHP page, SimpleProxy.php:

<?php
echo file_get_contents('http://localhost:4567');
?>

And in my XMLHttpRequest I use 'SimpleProxy.php' in place of 'http://localhost:4567', which effectively puts the request on the same domain as my .js code.

like image 111
HomerPlata Avatar answered Oct 23 '22 15:10

HomerPlata