Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax request to different host

i have the following javascript in my webpage:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.google.com', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    alert('resp received, status:' + xhr.status + ', responseText: ' + xhr.responseText);
  }                                                                       
};                                                                        
xhr.send(null);                                                           

this executes and finishes w/ a readyState of 4, status of 0, and empty responseText and responseXML. i know that it is actually sending the request b/c i tried sending the xhr to a server on my machine, and the server does in fact respond. why am i not getting anything in the responseText? does it have something to do w/ the fact that the xhr is going to a different server?

when i open up the js debugger and type 'xhr' to inspect the object i get this:

XMLHttpRequest
DONE: 4
HEADERS_RECEIVED: 2
LOADING: 3
OPENED: 1
UNSENT: 0
abort: function abort() {
addEventListener: function addEventListener() {
dispatchEvent: function dispatchEvent() {
getAllResponseHeaders: function getAllResponseHeaders() {
getResponseHeader: function getResponseHeader() {
onabort: null
onerror: null
onload: null
onloadstart: null
onprogress: null
onreadystatechange: function () {
open: function open() {
overrideMimeType: function overrideMimeType() {
readyState: 4
removeEventListener: function removeEventListener() {
responseText: ""
responseXML: null
send: function send() {
setRequestHeader: function setRequestHeader() {
status: 0
statusText: ""
upload: XMLHttpRequestUpload
withCredentials: false

like image 482
aaronstacy Avatar asked Jan 19 '26 03:01

aaronstacy


1 Answers

does it have something to do w/ the fact that the xhr is going to a different server?

Yep, you cannot send requests to another servers via AJAX. Whereas, you can send your requests from the server-side. Thus you'll need to implement following workflow: Your page -> Your server -> Third party server -> Your server -> Your page , where "->" means sending data.

like image 129
Li0liQ Avatar answered Jan 21 '26 20:01

Li0liQ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!