2

Possible Duplicate:
Please explain JSONP
On page 'www.foo.com', can a script loaded from 'www.example.com' send ajax requests to 'www.example.com'?

I need to make a request from a javascript to a php file.
The php file then pulls data from a database, and then sends the information back to the javascript.

I figured the best way to do this would be to make a javascript which uses XMLHTTP to ask the PHP script for the information. Both the Javascript file and PHP file are on the same host.

The catch is that I'm calling the javascript on a different domain. This means I can't set the XMLHTTP.open to a different domain because of the Same-Origin-Policy.

Am I out of luck even though technically both the javascript and php files are on the same host? What is the best way around this? I saw some mentions of using JSON.

The other catch is that I CAN NOT use jQuery. I know things would be easier if I could use jQuery -- but I can't.

This is a pretty close approximation of what I'm trying to do, with the exception being that my request has to be cross-domain:
http://www.w3schools.com/php/php_ajax_database.asp

Any ideas? I'm open to alternative solutions. Thanks!

2
  • If the PHP script & JS file are both on the same host, can you serve the PHP script from the same domain at all? Commented Aug 28, 2012 at 7:54
  • JsonP <- check this. With P at the end. See: Please explain JSONP
    – hakre
    Commented Aug 28, 2012 at 7:56

2 Answers 2

2

I think the focal point of your investigation should be the "domain mess":

  • For the client side, it is of no importance, whether the 2 domains are on the same host: Only the domain counts
  • For the server side, this ofcourse is different.

You might be trying to create some sort of interop between two applications on the same server - this might be achievable by some self-proxying or by simply creating an interop domain, loading the relevant parts from there.

1

I suggest you to use JSONP (http://en.wikipedia.org/wiki/JSONP) if HTTP GET is enough. (You don't need to send binary files to you server).

It's pretty simple idea. First you create a callback to process data from the server.

var callback = function(data) { alert('My name is ' + data.user) };

Then you add script element in the DOM:

<script src='http://external-domain.com/api.php'></script>

which returns json result wrapped with your callback function

callback({ user : Aaren });