Javascript cross-domain ajax request - status 200 OK, but no response

Here is my situation: I create a widget that site administrators can embed on their site, and the data is stored on my server. Thus, the script should basically make an ajax request to the php file on my server to update the database. Right? Right :) Ajax request works fine when I run it on local server but it does not work when the php file is on my ONLINE server. This is the im code using:

var url = "http://www.mydomain.net/ajax_php.php"; var params = "com=ins&id=1& mail=mymail@site.net "; 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); 

Firebug shows: http://www.mydomain.net/ajax_php.php 200 OK X 600ms.

When I check ajax responnseText, I always get the status: 0

Now my question is: β€œCan I execute cross-domain ajax requests by default? Could this be a cross-site ajax problem? Because it works when the requested file is on my local server, but DOES not work when the requested file is on another server, im thinks ajax requests to another remote server might be denied? Can you help me with this? Thanks ..

+4
source share
2 answers

Cross-domain requests are not directly allowed. However, there is a generally accepted JSONP method that will allow you to avoid this restriction using 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, for example:

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

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

Another method that I should have used from time to time is cross-documenting through an iframe. You can have one dialog with another, even cross-domain, with limited access through postMessage . Please note that only the latest browsers have this functionality, therefore the option is not viable in all cases, without resorting to hacking.

+2
source

You will need your response to be sent back to your client using a JSONP call.

What you need to do is get your request for data packed in a script tag. Your server will respond with your data included in the function call. By loading the script as an external resource, your browser will execute the script (like adding a link to an external JS file, such as jQuery) and pass the data to the famous JS method. Then your JS method will take the data and do whatever you need with it.

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

Hope this helps.

0
source

All Articles