views:

73

answers:

1

Edit: Maybe I made the question more complex than it should. My questions is this: How do you make API calls to a server from JS.

I have to create a very simple client that makes GET and POST calls to our server and parses the returned XML. I am writing this in JavaScript, problem is I don't know how to program in JS (started to look into this just this morning)!

As n initial test, I am trying to ping to the Twitter API, here's the function that gets called when user enters the URL http://api.twitter.com/1/users/lookup.xml and hits the submit button:

function doRequest() {
    var req_url, req_type, body;
    req_url = document.getElementById('server_url').value;
    req_type = document.getElementById('request_type').value;   
    alert("Connecting to url: " + req_url + " with HTTP method: " + req_type);
    req = new XMLHttpRequest();
    req.open(req_type, req_url, false, "username", "passwd");// synchronous conn
    req.onreadystatechange=function() {
            if (req.readyState == 4) {
                    alert(req.status);
            }
    }
    req.send(null);
}

When I run this on FF, I get a

Access to restricted URI denied" code: "1012

error on Firebug. Stuff I googled suggested that this was a FF-specific problem so I switched to Chrome. Over there, the second alert comes up, but displays 0 as HTTP status code, which I found weird.

Can anyone spot what the problem is? People say this stuff is easier to use with JQuery but learning that on top of JS syntax is a bit too much now.

+3  A: 

For security reasons, you cannot use AJAX to request a file from a different domain.

Since your Javascript isn't running on http://api.twitter.com, it cannot request files from http://api.twitter.com.

Instead, you can write server-side code on your domain to send you the file.

SLaks
What is the correct way to contact REST APIs using JS? The call I'm trying to make here is trivial to code in Java, I don't understand why it's so hard in JS.
recipriversexclusion
It's not a matter of difficulty, it's just [not allowed](http://en.wikipedia.org/wiki/Same_origin_policy). You have to use an Ajax-alternative request method, such as [JSONP](http://en.wikipedia.org/wiki/JSON#JSONP).
Jonathan Lonowski
@Jonathan and SLaks, maybe I'm misunderstanding, but what I'm trying to has nothing to do with accessing methods or files on a server, I'm just trying to send a GET request to the Twitter API.
recipriversexclusion
As far as the browser is concerned, there is no difference whatsoever between a file an a GET request to an API.
SLaks