Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST AJAX request to mongoDB

Tags:

jquery

mongodb

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?

like image 330
ilamaiolo Avatar asked Apr 23 '13 08:04

ilamaiolo


1 Answers

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.

like image 82
andyb Avatar answered Oct 26 '22 10:10

andyb