0

I am running MongoDB in the REST mode and trying to get query results from the MongoDB server through HTTP request. The following is the simple code that I have written:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <script type="text/javascript">
    function httpGet(theUrl){
        //document.write(theUrl);
        var xmlHttp = null;
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", theUrl, false);
        xmlHttp.send(null);
        document.getElementById("response").innerHTML=xmlHttp.responseText;
    }
    </script>
    <title>Connection</title>
</head>
<body>
    <button onclick="httpGet('http://127.0.0.1:28017/test/first/?limit=-1')" >
        Click
    </button>
    <p id="response"> </p>
</body>
</html>

But I am unable to get the response. Whereas when I copy and paste the URL in the address bar of the browser I get following as the response:

{
  "offset" : 0,
  "rows": [
       { "_id" : { "$oid" : "4d510086ce29000000007d5a" }, "date" : { "$date":60968917800000 } }
    ],

 "total_rows" : 1 ,
 "query" : {} ,
 "millis" : 0
}

Can someone help and tell me what could be the problem.

1 Answer 1

3

Is the page on which your code is running also loaded from 127.0.0.1 port 28017? If not, that's your problem, you're running into the Same Origin Policy.

If it is (both server and port are the same), I'd recommend using a relative URL, so your

httpGet('http://127.0.0.1:28017/test/first/?limit=-1')

becomes

httpGet('/test/first/?limit=-1')

Fundamentally, the code works: http://jsbin.com/awose3


Off-topic: I'd strongly recommend not using synchronous XHR calls (ajax requests). They lock up the UI of the browser while they're in process, and of course they can take a second or two (or ten) to run, during which the user experience is unpleasant to say the least. Instead, use an asynchronous call and a callback on onreadystatechange, like this (obviously, error handling and other complexities have been left out):

function httpGet(theUrl){
    //document.write(theUrl);
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.onreadystatechange = handleReadyStateChange;
    xmlHttp.send(null);

    function handleReadyStateChange() {
      if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
          document.getElementById("response").innerHTML=xmlHttp.responseText;
        }
      }
    }
}

Live example


Off-topic 2: I'd suggest looking at a library like jQuery, Prototype, YUI, Closure, or any of several others. They'll smooth over browser quirks, simplify various things, and add a number of useful features so that you can concentrate on solving the actual problem you're trying to solve, rather than worrying about things like (random example) Safari mis-reporting the default selected value of an option, and Internet Explorer's habit of leaking memory on event handlers unless you chant, burn incense, and periodically get up and twirl three times as you write your code.

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

8 Comments

Thank you for such a wonderful response.I did not completely get the first part of your message. I am a bit confused but I'll look into it and yes I am looking into jQuery and YUI for past couple of days. If you could please suggest me a source (apart from the Yahoo Developer Network) from where I could read about VUI it be great.
@aditya: No worries, glad that helped. Re the SOP: JavaScript code isn't allowed to load content via XHR from anywhere it likes, only from the same "origin" as the document in which the code is running. See the link for details. "Origin" is fairly strictly defined (the protocol [http / https], server, and port must all match). There are ways around it: JSON-P is a popular one, or if you can control both the server and the browser that the client will use, CORS.
@aditya: (continuing) Re libraries: I don't have any other info on YUI, but as it's a Yahoo! project, the YDN is going to be your best source of info anyway. I would look closely at jQuery and the associated jQuery UI. It's free and open source, has good corporate sponsorship (and so there are people paid to work on the library), has incredible penetration in the community (read: lots and lots of people to help you), and works well. I am/was also a fan of Prototype, but the lack of a corporate sponsor has really hurt the project (in my view).
@Crowder: You replies had been really helpful. At the moment I am facing a situation which is something like this: the mongoDB interface is listening at port: 28017. So how will I been able to run the script on same port. Sorry for bothering you, I am new to all this.
@Crowder: I have read that JSON-P has some security concerns, is it true?
|

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.