0

I opened Firefox's scratchpad and entered...

function ajaxRequest()
{
var xmlhttp;
var domainName = location.host;
var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName=';
url = url + domainName + '&x=' + Math.random(); // x= to avoid browser caching;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    alert(domainName+'='+xmlhttp.responseText);
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

ajaxRequest();

How come my ajax code works in the same domain as the remote script (http://leke.dyndns.org), but not in other domains (like http://stackoverflow.com)?

If it helps, here is the cgi side...

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os, cgi, cgitb, socket
cgitb.enable()

cgiData = cgi.FieldStorage() # Domain Name
domainName = cgiData.getvalue('domainName')
ipa = socket.gethostbyaddr(domainName)
sendIpa = ipa[2][0]

print 'Content-Type: text/html;charset=utf-8'
print ""
print sendIpa
user569548
  • 61
  • 4

2 Answers2

2

No, it won't. This is by design (the same origin policy) and is to prevent cross site scripting attacks.

You can get around it using JSONP if you really must, but it's not recommended because you are potentially allowing another site (which may be hacked by attackers even if you trust the site admins) to do whatever they like with the logged in user's data.

Matt Gibson
  • 14,616
  • 7
  • 47
  • 79
1

In normal ways it can not be done. But it is possible to run if server side code is hosted on a different domain

To achieve this you have to make below server site changes :

In the server site you have to set Access-Control-Allow-Origin as Response Header

Access-Control-Allow-Origin : * //all other domain can access

or 

Access-Control-Allow-Origin : <your_domain_name> // only your domain can access

Check : https://developer.mozilla.org/en/http_access_control

[Example]

you can make a successful ajax call to http://xyz.com?x=a url from different domain. If and ony if http://xyz.com?x=a url's response header has Access-Control-Allow-Origin field with your domain name or '*'.

selladurai
  • 6,491
  • 14
  • 56
  • 88
mukul.das
  • 21
  • 4