Altin
Altin

Reputation: 2245

Cross domain javascript ajax request - status 200 OK but no response

Here is my situation: Im creating a widget that site admins can embed in their site and the data are stored in my server. So the script basically has to make an ajax request to a php file in my server to update the database. Right? Right :) The ajax request works excellent when i run it in my local server but it does not work when the php file is on my ONLINE server. This is the code im using:

var url = "http://www.mydomain.net/ajax_php.php";
var params = "com=ins&id=1&[email protected]";
http.async = true;
http.open("POST", url, true);       

http.onreadystatechange = function() {

    if(http.readyState == 4 && http.status == 200) {

    //do my things here
    alert( http.responseText ); 

    }
}
http.send(params);

In firebug it shows: http://www.mydomain.net/ajax_php.php 200 OK X 600ms.

When i check the ajax responnseText I always get a Status:0

Now my question is: "Can i do cross-domain ajax requests by default? Might this be a cross-domain ajax problem? Since it works when the requested file resides in my local server but DOESN'T work when the requested file is in another server, im thinking ajax requests to another remote server might be denied? Can you help me clear on this? Thanks..

Upvotes: 4

Views: 7984

Answers (2)

David Hoerster
David Hoerster

Reputation: 28701

You're going to need to have your response sent back to your client via a JSONP call.

What you'll need to do is to have your request for data wrapped in a script tag. Your server will respond with your data wrapped in a function call. By downloading the script as an external resource, your browser will execute the script (just like adding a reference to an external JS file like jQuery) and pass the data to a known JS method. Your JS method will then take the data and do whatever you need to do with it.

Lots of steps involved. Using a library like jQuery provides a lot of support for this.

Hope this helps.

Upvotes: 0

Jacob
Jacob

Reputation: 78900

Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:

function receiveData(data) {
    // ...
}

And then your server wraps JSON data in a function call, like this:

receiveData({"the": "data"});

And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.

Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.

Upvotes: 2

Related Questions