Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to CouchDB using Javascript?

I have seen a couple of such questions and read tutorials I could find. Unfortunately they all suppose I have some knowledge of something that I actually don't have and I don't even know the keywords of what I don't know.

I have a HTML page with some javascript in it. I can put the information in a string or javascript object. Now, how do I get it to my DB? How do I point where my DB is and how can the javascript authorize to the db so it could write?

Most of the tutorials only show how CouchDB works with the curl thing and I haven't seen a tutorial to make website interact with the database. Isn't that what CouchDB is meant for?

like image 738
Džuris Avatar asked Mar 25 '13 13:03

Džuris


1 Answers

Sending REST requests from JavaScript (with jQuery) is very similar to what you would do with curl:

function create() {
  var o = {"name":"Bond"};
  $.ajax({
   type: "POST",
   url: "/myDB/",
   contentType: "application/json",
   data: JSON.stringify(o),
   dataType: "json",
   success: function(data) {
     alert(data.id + " created !");
   }
  });
}

But be careful: the request will be blocked for security reasons if it is not retrieved from the same service as CouchDB. So put your HTML page as an attachment of your design document.

You will learn later how to use such scripts in "shows" or "lists". But let's begin with something simple.

like image 160
Aurélien Avatar answered Sep 22 '22 21:09

Aurélien