8

I am trying to fire a XMLHttpRequest to mongoDB to retrieve a document via AJAX.

This is my code:

function getJsonDocumentByModeldid(model_id) {
    var valoreInput = document.getElementById('inputModelId').value;
    alert(valoreInput);

    $.ajax({
      url: "http://localhost:28017/test/",
      type: "get",
      //data: "filter_a=" + valoreInput,
      dataType: 'jsonp',
      crossDomain: true,

      success: function (data) {
        alert("success");
        //var json2javascript = $.parseJSON(data);
        manageLayout();
      },

      error: function (XMLHttpRequest, textStatus, errorThrown) {
       alert("Status: " + textStatus + "    Error:" + errorThrown);
      }
  });
}

My function always returns an error. So what is the problem?

andyb
  • 43,435
  • 12
  • 121
  • 150
ilamaiolo
  • 345
  • 2
  • 4
  • 14
  • the ajax request fails with the script, instead if i copy url in browser, the server response with success. i don't know what is the problem... – ilamaiolo Apr 23 '13 at 08:52
  • The alert error is Jqueryxxxxxx was not called! – ilamaiolo Apr 23 '13 at 08:55
  • yes.. i start the server with the command mongod --rest. i try with datatype json,but the problem persist – ilamaiolo Apr 23 '13 at 12:51
  • Is the page that your JavaScript is running on loaded from a web server (running locally) or just a simple HTML page loaded in a browser? It might be the [Same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) problem. – andyb Apr 23 '13 at 13:34
  • is a simple page loaded in a browser..this is my step: 1)launch the server in windows terminal with the command "mongod.exe --rest" 2)if i click http://127.0.0.1:28017/ilariodb/ilariodb/?filter_name=mongo, i have the response. if instead i launch my script the ajax request go in error! how i can load my web page which include a script for the response in mongodb's web server? – ilamaiolo Apr 24 '13 at 10:19

2 Answers2

7

This functionality is supported as part of the Simple (read-only) REST Interface but to make cross domain requests the --jsonp otherwise you will be subject to the Same origin policy problem, since the IP address and port that you are making the request from do not match the IP address and port that mongoDB is running on.

Start mongoDB with mongod.exe --rest --jsonp (plus any other options you may have).

The following example page can be served via a web sever (for example Apache HTTP Server) or simply saved locally and loaded in the browser as a file. The request is for information about a dbCollection called andyb, which I created in mongoDB first with:

db.createCollection('andyb');

HTML

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>mongoDB AJAX demo</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
  <script type='text/javascript'>//<![CDATA[
  $(function(){
    $.ajax({
      url: 'http://localhost:28017/local/andyb',
      type: 'get',
      dataType: 'jsonp',
      jsonp: 'jsonp', // mongod is expecting the parameter name to be called "jsonp"
      success: function (data) {
        console.log('success', data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log('error', errorThrown);
      }
    });
  });//]]>
  </script>
</head>
<body>
</body>
</html>

Many browsers support CORS now which is an alternative (more modern) way to facilitate cross domain resources.

andyb
  • 43,435
  • 12
  • 121
  • 150
0

The previous answer can be modified by using deferred objects (see this good guide: "How do I return the response from an asynchronous call?):

<!doctype html>
<meta charset="utf-8">
<title>mongoDB AJAX demo</title>
<script src="http://code.jquery.com/jquery-latest.min.js" ></script>
<script>    
    $(function(){ 
    // add rest = true and jsonp = true to /etc/mongodb.conf, 
    // then restart mongodb
         $.ajax({
                url: "http://localhost:28017/local/startup_log/",
                type: 'get',
                dataType: 'jsonp',
                jsonp: 'jsonp', // mongodb is expecting that                                                                                     
            })
            .done(function(data) {
                d=JSON.stringify(data,undefined,1);
                $("code").text(d).css("color","green");
            })
            .fail(function(request,status,error) {
                $("code").text("get failed: "+error).css("color","red");
            })
            .always(function() {
                console.log("finished")
            })

  });
</script>
<body>
  <pre>
    <code>
    </code>
  </pre>

Anyway, in both situations the error: and fail() handling works only if a port is not provided. For instance:

url:"localhost/asdasdasd"

results in an error handling; while

url:"localhost:28017/asdasdasd"

results in a 404 log in the console, like this:

GET http://localhost:28017/?jsonp=jQuery110207253803350031376_1383522587177&_=1383522587178 404 (OK) 
Community
  • 1
  • 1
leonard vertighel
  • 1,058
  • 1
  • 18
  • 37