15

Is there a way to call a url and get a response using javascript? I need the equivalent of ASP.NET:

WebRequest req = HttpWebRequest.Create("http://someurl.com");
WebResponse webResponse = req.GetResponse();

I have an external url that holds some information I need and I want to call this url from javascript and parse the response in order to determine what to do in my application.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
lnetanel
  • 1,118
  • 3
  • 13
  • 28
  • 4
    FYI: JavaScript can only talk to the same domain. You can get away with JSON calls to others, but better to use a proxy. – epascarello May 25 '09 at 14:18

4 Answers4

20

You can make an AJAX request if the url is in the same domain, e.g., same host different application. If so, I'd probably use a framework like jQuery, most likely the get method.

$.get('http://someurl.com',function(data,status) {
      ...parse the data...
},'html');

If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you. Do your request to your server using AJAX, have the server request and return the response from the external host.

Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
5
var req ;

// Browser compatibility check          
if (window.XMLHttpRequest) {
   req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {

 try {
   req = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {

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

}


var req = new XMLHttpRequest();
req.open("GET", "test.html",true);
req.onreadystatechange = function () {
    //document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
}

req.send(null);
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
NinethSense
  • 8,824
  • 2
  • 23
  • 23
2

Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.

In jQuery:

$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })

In plain vanilla javaScript (from w3c):

var xmlhttp;
function loadXMLDoc(url)
{
    xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for all new browsers
      xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
  }
else
  {
      alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
    if (xmlhttp.readyState==4)
      {// 4 = "loaded"
          if (xmlhttp.status==200)
            {// 200 = OK
             //xmlhttp.data and shtuff
            // ...our code here...
        }
  else
        {
            alert("Problem retrieving data");
        }
  }
}
Dmitri Farkov
  • 9,133
  • 1
  • 29
  • 45
2

If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.

You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.

<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
                                             // i'm just showing an example.
echo $contents;
?>

If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.

Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.

nickf
  • 537,072
  • 198
  • 649
  • 721
  • If you want to call a resource located on a different domain, or even a different sub-domain, you'll need to use some sort of work-around. See Yahoo's example of a proxy file in PHP: http://developer.yahoo.com/javascript/howto-proxy.html Snook has a good overview of workarounds with AJAX calls done cross-domain. See http://snook.ca/archives/javascript/cross_domain_aj/ – Razvan Caliman May 25 '09 at 14:42