Reputation: 2254
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?
Upvotes: 5
Views: 7489
Reputation: 1886
Just because I had so much trouble finding a clear answer on this too, here's how to do it in vanilla JS:
const URL = "http://127.0.0.1:5984"
function createDB(dbName) {
var req = new XMLHttpRequest();
req.open("PUT", URL + "/" + dbName, true);
req.setRequestHeader("Content-type", "application/json");
req.send();
}
function updateDB(dbName, docName, data) {
var req = new XMLHttpRequest();
req.open("PUT", URL + '/' + dbName + '/' + docName, true);
req.setRequestHeader("Content-type", "application/json");
req.send(JSON.stringify(data));
}
So you'd use them like this:
createDB('baseball');
updateDB('baseball', 'document', {"pitcher":"Nolan Ryan"});
Note: I'm not going to get into revision numbers and conflict resolution here, just supplying some really basic code. The second time you try to update the same record, there will be a conflict unless you supply the correct revision number, FYI.
updateDB('baseball', 'document', {"_rev":"1-7e007b1ef348cba88396435479822386", "pitcher":"Roger Clemens"});
Upvotes: 5
Reputation: 3852
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.
Upvotes: 6
Reputation: 18572
Checkout jquery.couch.js
: https://github.com/daleharvey/jquery.couch.js-docs
Documentation is here: http://daleharvey.github.com/jquery.couch.js-docs/symbols/
Upvotes: 3