DarkMark
DarkMark

Reputation: 41

XMLHttpRequest responseText is empty

I have read much on this site, but I can't solve my problem! :( It must be very easy but it does not work!

The problem is http.responseText is empty.

I'm using the webspace on http://www.000webhost.com

Is it posible to get a String with the Sourcecode of www.google.de?

Thanks for any help!

<html> 
<title>Test Site</title>
<body>
<h1>My Example</h1>
<script type="text/javascript">

var http = new XMLHttpRequest();

http.open("GET", 'https://www.google.de', true);
http.send(null);

http.onreadystatechange = function() {
    alert(http.responseText);
}

alert("The end is reached");
</script> 


<b>Here is some more HTML</b> 
</body>
</html>

Upvotes: 1

Views: 5938

Answers (2)

Kishorevarma
Kishorevarma

Reputation: 956

its not possible with ajax because of same origin policy , but to solve your problem you can use server side programming like PHP or Nodejs. basically PHP will be available in web hostings.

create getGoogle.php

 <?php 
    // create curl resource 
    $ch = curl_init(); 

    // set url 
    curl_setopt($ch, CURLOPT_URL, "www.google.de"); 

    //return the transfer as a string 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    // $output contains the output string 
    $output = curl_exec($ch); 

    // close curl resource to free up system resources 
    curl_close($ch);  

    echo $output;    
  ?>

use your javascript as below

  <script type="text/javascript">

  var http = new XMLHttpRequest();

   http.open("GET", 'getGoogle.php', true);
   http.send(null);

   http.onreadystatechange = function() {
        alert(http.responseText);
   }

   alert("The end is reached");
   </script>

Hope this solves your problem. Cheers

Upvotes: 1

SteveP
SteveP

Reputation: 19103

Making client side http requests is limited by the browser to only allowing requests from the same server that supplied the original page. This is what is being referred to as the Same Origin Policy.

As mentioned by others, this is normally done by requesting the URL in your server side code.

Upvotes: 0

Related Questions