0

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.

4

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
It's not a matter of difficulty, it's just not allowed. You have to use an Ajax-alternative request method, such as JSONP.
@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.
As far as the browser is concerned, there is no difference whatsoever between a file an a GET request to an API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.