Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data to couchdb with jsonp response

Tags:

jsonp

couchdb

Is there a way add data to a couchdb that runs on another domain and get back an response whether the operation was successfully or not? I know couchdb supports jsonp callback but can I add data with this approach?

like image 489
Andreas Köberle Avatar asked Jul 23 '10 11:07

Andreas Köberle


2 Answers

No, you cannot currently do this. CouchDB's REST API requires a POST or PUT request in order to insert data, but JSONP only supports GET requests. So you can retrieve data from CouchDB across domains, but updates/inserts/deletes won't work.

like image 81
Mark Bell Avatar answered Oct 15 '22 08:10

Mark Bell


You can use client-side javascript to make a form to do the POST, direct the output to an iframe, and use cross-window iframe messaging to get the result.

Of course, someone has already made a nice javascript library to do this. Get the code here: https://github.com/benvinegar/couchdb-xd

Follow the instructions to push it as an additional database on your couchdb server. Then, on any site, include one not in the 'your-couch-server' domain, you can do the following (just try it in the javascript console):

jQuery.getScript(
    "http://YOUR-COUCH-SERVER/couchdb-xd/_design/couchdb-xd/couchdb.js", 
    function() {
        Couch.init(
            function() { 
                var s = new Couch.Server('http://YOUR-COUCH-SERVER/'); 
                var d = new Couch.Database(s,'YOURDB'); 
                d.put(
                    "stackoverflow-test 1", 
                    { foo: 111, bar: 222 },
                    function(resp) {
                        console.log(resp);          
                    } 
                );
            }
        )
    }
);

The above presumes you have jquery is already loaded on the page. If not, you'll need to add it however you're currently interacting with the other page.

The library only works on modern browsers with window.postMessage() support, though a small patch may eventually allow older browsers to use it via src/hash communication.

like image 28
Scott Smith Avatar answered Oct 15 '22 08:10

Scott Smith