0

I want to catch cross domain response in pure javascript ajax not using jquery or other external libraries.

var xmlhttp, response;

try {
    xmlhttp = new XMLHttpRequest(); 
} catch(e) { 

   try { 
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e2) { 

       try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
    }
}

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4) { 
        if(callback != undefined) { 
              console.log(xmlhttp.responseText);
        }
    }
}

url = "http://xxxx.com/layer.php?callback=callRes";
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader("Content-Type",
                    "application/json,application/javascript,text/javascript");
xmlhttp.send();

spent lots of time and googling but not find any solution

suggestions are most welcome but not script method only pure javascript ajax

dee-see
  • 23,668
  • 5
  • 58
  • 91
Man Programmer
  • 5,300
  • 2
  • 21
  • 21
  • 1
    Should not be possible. The Same Origin Policy can only be avoided by the use of some Browser Plugins. Why not JSONP? – XQDev Jul 31 '14 at 13:37
  • It would ***have*** to be JSONP. – MackieeE Jul 31 '14 at 13:38
  • as i mentioned in my question i want to use pure javascript ajax not script method – Man Programmer Jul 31 '14 at 13:45
  • Where is the response coming from? Do you have access to adjust the headers? If so use CORS and adjust the headers to allow your front end code access. This can even be accomplished on S3 if the resource you're requesting is on there. – ness-EE Jul 31 '14 at 13:52
  • Do you have access to this file http://xxxx.com/layer.php ? – hex494D49 Jul 31 '14 at 13:52
  • Well, I'm afraid you can't do that. If they don't allow/provide a way to do it. – hex494D49 Jul 31 '14 at 14:06
  • but i getting the callback response "response({"msg_arr":{"user_email":"Please enter valid email ID.","user_name":"Pick a bigger username. Atleast 5 characters.","user_country_code":"Country code required.","user_mobile_number":"Mobile number required."},"msg_type":"error"})" but unable to catch in variable – Man Programmer Jul 31 '14 at 14:07

1 Answers1

0

I assume you want to see the response in console.

Before calling console.log() you are checking to see if callback exists. In the given piece of code callback is not yet defined so maybe this is the only barrier preventing the output of xmlhttp.responseText.

Solution: remove if (callback != undefined) and just call console.log(xmlhttp.responseText)

ness-EE
  • 1,334
  • 13
  • 19
chm-software.com
  • 351
  • 2
  • 10