Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read continuous feed from CouchDB using Ajax/jQuery

I want to listen for continuous changes from CouchDB using jQuery - now this works:

http://localhost:5984/testdb/_changes?feed=continuous

which means that I get a new line of json every time there is a db update - but how do I read updates off this URL using jQuery?

I tried using this but it doesn't work:

$.ajax(
{
  url : "http://localhost:5984/testdb/_changes?feed=continuous&callback=?",
  dataType : 'json',
  success : function(data)
  {
    alert(data.results.length);
  }
});

Edit: $.ajax calls the "success" function and returns immediately, it doesn't "poll" for changes.. (timeline column for ajax column in image below is 16ms)

alt text

And no, it isn't a cross-domain ajax problem - I can see in fireBug there is a response with the right number of elements

So any guidance/advice would be appreciated - it doesn't have to be jQuery - plain old javscript would do as well

like image 611
sami Avatar asked Nov 14 '22 05:11

sami


1 Answers

Off the top of my head, I can think of two good ways to do this.

  1. Using a timer (ie., setTimeout();), run the AJAX call on the changes feed every X seconds. You will also store the last sequence number that you received, so that you can tell the changes feed which sequence number to start at the next time you poll. This will prevent duplicate data and make the responses smaller.

  2. Depending on what browsers you need to support, you might be able to use the EventSource API. Here is a jQuery implementation: https://github.com/rwldrn/jquery.eventsource

like image 156
Sam Bisbee Avatar answered Dec 09 '22 16:12

Sam Bisbee