mac389
mac389

Reputation: 3133

Accessing Cloudant database with jQuery

I'm trying to connect to my CouchDB on Cloudant using jQuery and jQuery.couch.sj

However, I can't even get the most basic info about my database. For example the following code prints nothing to the console.

Code

<script>
$.couch.urlPrefix ="https://acharya.cloudant.com";
$.couch.info({
success: function(data) {
    console.log(data);
}
});
</script>

I've looked at the online documentation but to no avail.

If I type

var db= $.couch.db("toxtweet");
console.debug(db);

to see something about one of my CouchDB's, I get:

Object { name="toxtweet",uri="https://acharya.cloudant.com/toxtweet/", compact=function(), 
more...}

And that is the correct URI. So, how would I, for example, get the number of documents in the "toxtweet" database? Trying the example doesn't work.

Update If I view the page in Chrome instead of Firefox I see the following error.

XMLHttpRequest cannot load https://acharya.cloudant.com/. Origin http://tox.sinaiem.org is not  
allowed by Access-Control-Allow-Origin.

I thought that Cloudant was a CouchApp that bypassed the same-origin policy.

Upvotes: 0

Views: 2193

Answers (2)

Simon Metson
Simon Metson

Reputation: 81

CouchApp's/Cloudant don't bypass same origin policy. If you have a CouchApp on Cloudant you can access it under your domain (e.g. https://acharya.cloudant.com/DB_NAME/_design/DESIGN/index.html), if you want that on another domain you'll need a reverse proxy as AndyD suggests.

The CouchDB wiki has two nice run throughs for using HTTPD or Nginx as a reverse proxy, both should apply when running against a database hosted in Cloudant.

HTH

Simon

Upvotes: 1

AndyD
AndyD

Reputation: 5385

I haven't used jquery to access Cloudant, but I would expect you to have to log in somewhere first unless you have somehow made your database public.

Have you checked in Chrome or Firefox what https requests and responses jquery.couch is sending and receiving?

To get the number of documents, you would typically have a view with a reduce method like this:

// map
function(doc) {
 emit(doc.id, 1);
}

// reduce
function(keys, values, rereduce) {
  return sum(values);
}

see here for more info What is the CouchDB equivalent of the SQL COUNT(*) aggregate function?

I would recommend you use Futon when trying out examples before doing an equivalent request in jquery.couch

Update

Have you tried JSONP to get around cross domain issue? see here: http://support.cloudant.com/customer/portal/articles/359321-how-do-i-read-and-write-to-my-cloudant-database-from-the-browser-

Upvotes: 1

Related Questions