plugins: updated resource selected to receive proper updates from the query
[myslice.git] / manifold / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
13 function debug_query (msg, query) {
14     if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15     else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16     else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17     else messages.debug ("debug_query: " + msg + " query= " + query);
18 }
19
20 /* ------------------------------------------------------------ */
21
22 // Constants that should be somehow moved to a plugin.js file
23 var FILTER_ADDED   = 1;
24 var FILTER_REMOVED = 2;
25 var CLEAR_FILTERS  = 3;
26 var FIELD_ADDED    = 4;
27 var FIELD_REMOVED  = 5;
28 var CLEAR_FIELDS   = 6;
29 var NEW_RECORD     = 7;
30 var CLEAR_RECORDS  = 8;
31 var FIELD_STATE_CHANGED = 9;
32
33 var IN_PROGRESS    = 101;
34 var DONE           = 102;
35
36 /* Update requests from plugins */
37 var SET_ADD        = 201;
38 var SET_REMOVED    = 202;
39 var RUN_UPDATE     = 203;
40
41 // request
42 var FIELD_REQUEST_CHANGE  = 301;
43 var FIELD_REQUEST_ADD     = 302;
44 var FIELD_REQUEST_REMOVE  = 303;
45 // status
46 var FIELD_REQUEST_PENDING = 301;
47 var FIELD_REQUEST_SUCCESS = 302;
48 var FIELD_REQUEST_FAILURE = 303;
49
50 /* Query status */
51 var STATUS_NONE               = 500; // Query has not been started yet
52 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
53 var STATUS_GET_RECEIVED       = 502; // Success
54 var STATUS_GET_ERROR          = 503; // Error
55 var STATUS_UPDATE_PENDING     = 504;
56 var STATUS_UPDATE_IN_PROGRESS = 505;
57 var STATUS_UPDATE_RECEIVED    = 506;
58 var STATUS_UPDATE_ERROR       = 507;
59 // outdated ?
60
61
62 // A structure for storing queries
63
64
65
66 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
67
68     /* Constructor */
69     if (typeof query == "undefined")
70         throw "Must pass a query in QueryExt constructor";
71     this.query            = query
72     this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext
73     this.main_query_ext   = (typeof main_query_ext   == "undefined") ? null : main_query_ext
74     this.update_query_ext = (typeof update_query_ext   == "undefined") ? null : update_query_ext
75     this.disabled         = (typeof update_query_ext   == "undefined") ? false : disabled
76     
77     this.status       = null;
78     this.results      = null;
79     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
80 }
81
82 function QueryStore() {
83
84     this.main_queries     = {};
85     this.analyzed_queries = {};
86
87     /* Insertion */
88
89     this.insert = function(query)
90     {
91         // We expect only main_queries are inserted
92
93         /* If the query has not been analyzed, then we analyze it */
94         if (query.analyzed_query == null) {
95             query.analyze_subqueries();
96         }
97
98         /* We prepare the update query corresponding to the main query and store both */
99         /* Note: they have the same UUID */
100
101         // XXX query.change_action() should become deprecated
102         update_query = query.clone();
103         update_query.action = 'update';
104         update_query.analyzed_query.action = 'update';
105         update_query.params = {};
106         update_query_ext = new QueryExt(update_query);
107         console.log("Update query created from Get query", update_query);
108
109         /* We store the main query */
110         query_ext = new QueryExt(query, null, null, update_query_ext, false);
111         manifold.query_store.main_queries[query.query_uuid] = query_ext;
112         /* Note: the update query does not have an entry! */
113
114
115         // The query is disabled; since it is incomplete until we know the content of the set of subqueries
116         // XXX unless we have no subqueries ???
117         // we will complete with params when records are received... this has to be done by the manager
118         // SET_ADD, SET_REMOVE will change the status of the elements of the set
119         // UPDATE will change also, etc.
120         // XXX We need a proper structure to store this information...
121
122         // We also need to insert all queries and subqueries from the analyzed_query
123         // XXX We need the root of all subqueries
124         query.iter_subqueries(function(sq, data, parent_query) {
125             if (parent_query)
126                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
127             else
128                 parent_query_ext = null;
129             // XXX parent_query_ext == false
130             // XXX main.subqueries = {} # Normal, we need analyzed_query
131             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
132             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
133         });
134
135         // XXX We have spurious update queries...
136     }
137
138     /* Searching */
139
140     this.find_query_ext = function(query_uuid)
141     {
142         return this.main_queries[query_uuid];
143     }
144
145     this.find_query = function(query_uuid)
146     {
147         return this.find_query_ext(query_uuid).query;
148     }
149
150     this.find_analyzed_query_ext = function(query_uuid)
151     {
152         return this.analyzed_queries[query_uuid];
153     }
154
155     this.find_analyzed_query = function(query_uuid)
156     {
157         return this.find_analyzed_query_ext(query_uuid).query;
158     }
159 }
160
161 /*!
162  * This namespace holds functions for globally managing query objects
163  * \Class Manifold
164  */
165 var manifold = {
166
167     /************************************************************************** 
168      * Helper functions
169      **************************************************************************/ 
170
171     separator: '__',
172
173     spin_presets: {},
174
175     spin: function(locator, active /*= true */) {
176         active = typeof active !== 'undefined' ? active : true;
177         try {
178             if (active) {
179                 $(locator).spin(manifold.spin_presets);
180             } else {
181                 $(locator).spin(false);
182             }
183         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
184     },
185
186     /************************************************************************** 
187      * Metadata management
188      **************************************************************************/ 
189
190      metadata: {
191
192         get_table: function(method)
193         {
194             var table = MANIFOLD_METADATA[method];
195             return (typeof table === 'undefined') ? null : table;
196         },
197
198         get_columns: function(method)
199         {
200             var table = this.get_table(method);
201             if (!table) {
202                 return null;
203             }
204
205             return (typeof table.column === 'undefined') ? null : table.column;
206         },
207
208         get_key: function(method)
209         {
210             var table = this.get_table(method);
211             if (!table)
212                 return null;
213
214             return (typeof table.key === 'undefined') ? null : table.key;
215         },
216
217
218         get_column: function(method, name)
219         {
220             var columns = this.get_columns(method);
221             if (!columns)
222                 return null;
223
224             $.each(columns, function(i, c) {
225                 if (c.name == name)
226                     return c
227             });
228             return null;
229         },
230
231         get_type: function(method, name)
232         {
233             var table = this.get_table(method);
234             if (!table)
235                 return null;
236
237             return (typeof table.type === 'undefined') ? null : table.type;
238         }
239
240      },
241
242     /************************************************************************** 
243      * Query management
244      **************************************************************************/ 
245
246     query_store: new QueryStore(),
247
248     // XXX Remaining functions are deprecated since they are replaced by the query store
249
250     /*!
251      * Associative array storing the set of queries active on the page
252      * \memberof Manifold
253      */
254     all_queries: {},
255
256     /*!
257      * Insert a query in the global hash table associating uuids to queries.
258      * If the query has no been analyzed yet, let's do it.
259      * \fn insert_query(query)
260      * \memberof Manifold
261      * \param ManifoldQuery query Query to be added
262      */
263     insert_query : function (query) { 
264         // NEW API
265         manifold.query_store.insert(query);
266
267         // FORMER API
268         if (query.analyzed_query == null) {
269             query.analyze_subqueries();
270         }
271         manifold.all_queries[query.query_uuid]=query;
272     },
273
274     /*!
275      * Returns the query associated to a UUID
276      * \fn find_query(query_uuid)
277      * \memberof Manifold
278      * \param string query_uuid The UUID of the query to be returned
279      */
280     find_query : function (query_uuid) { 
281         return manifold.all_queries[query_uuid];
282     },
283
284     /************************************************************************** 
285      * Query execution
286      **************************************************************************/ 
287
288     // trigger a query asynchroneously
289     proxy_url : '/manifold/proxy/json/',
290
291     asynchroneous_debug : true,
292
293     /**
294      * \brief We use js function closure to be able to pass the query (array)
295      * to the callback function used when data is received
296      */
297     success_closure: function(query, publish_uuid, callback /*domid*/)
298     {
299         return function(data, textStatus) {
300             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
301         }
302     },
303
304     // Executes all async. queries
305     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
306     asynchroneous_exec : function (query_publish_dom_tuples) {
307         // start spinners
308
309         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
310         //try {
311         //    if (manifold.asynchroneous_debug) 
312         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
313         //    jQuery('.need-spin').spin(manifold.spin_presets);
314         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
315         
316         // Loop through input array, and use publish_uuid to publish back results
317         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
318             var query=manifold.find_query(tuple.query_uuid);
319             var query_json=JSON.stringify (query);
320             var publish_uuid=tuple.publish_uuid;
321             // by default we publish using the same uuid of course
322             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
323             if (manifold.asynchroneous_debug) {
324                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
325                 messages.debug("... ctd... with actual query= " + query.__repr());
326             }
327
328             query.iter_subqueries(function (sq) {
329                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
330             });
331
332             // not quite sure what happens if we send a string directly, as POST data is named..
333             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
334                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
335         })
336     },
337
338     /**
339      * \brief Forward a query to the manifold backend
340      * \param query (dict) the query to be executed asynchronously
341      * \param callback (function) the function to be called when the query terminates
342      * Deprecated:
343      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
344      */
345     forward: function(query, callback /*domid*/) {
346         var query_json = JSON.stringify(query);
347         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
348     },
349
350     /*!
351      * Returns whether a query expects a unique results.
352      * This is the case when the filters contain a key of the object
353      * \fn query_expects_unique_result(query)
354      * \memberof Manifold
355      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
356      */
357     query_expects_unique_result: function(query) {
358         /* XXX we need functions to query metadata */
359         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
360         /* TODO requires keys in metadata */
361         return true;
362     },
363
364     /*!
365      * Publish result
366      * \fn publish_result(query, results)
367      * \memberof Manifold
368      * \param ManifoldQuery query Query which has received results
369      * \param array results results corresponding to query
370      */
371     publish_result: function(query, result) {
372         if (typeof result === 'undefined')
373             result = [];
374
375         // NEW PLUGIN API
376         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
377         $.each(result, function(i, record) {
378             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
379         });
380         manifold.raise_record_event(query.query_uuid, DONE);
381
382         // OLD PLUGIN API BELOW
383         /* Publish an update announce */
384         var channel="/results/" + query.query_uuid + "/changed";
385         if (manifold.asynchroneous_debug)
386             messages.debug("publishing result on " + channel);
387         jQuery.publish(channel, [result, query]);
388     },
389
390     /*!
391      * Recursively publish result
392      * \fn publish_result_rec(query, result)
393      * \memberof Manifold
394      * \param ManifoldQuery query Query which has received result
395      * \param array result result corresponding to query
396      */
397     publish_result_rec: function(query, result) {
398         /* If the result is not unique, only publish the top query;
399          * otherwise, publish the main object as well as subqueries
400          * XXX how much recursive are we ?
401          */
402         if (manifold.query_expects_unique_result(query)) {
403             /* Also publish subqueries */
404             jQuery.each(query.subqueries, function(object, subquery) {
405                 manifold.publish_result_rec(subquery, result[0][object]);
406                 /* TODO remove object from result */
407             });
408         }
409         manifold.publish_result(query, result);
410     },
411
412     // if set domid allows the result to be directed to just one plugin
413     // most of the time publish_uuid will be query.query_uuid
414     // however in some cases we wish to publish the result under a different uuid
415     // e.g. an updater wants to publish its result as if from the original (get) query
416     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
417         // xxx should have a nicer declaration of that enum in sync with the python code somehow
418
419         /* If a callback has been specified, we redirect results to it */
420         if (!!callback) { callback(data); return; }
421
422         if (data.code == 2) { // ERROR
423             // We need to make sense of error codes here
424             alert("Your session has expired, please log in again");
425             window.location="/logout/";
426             return;
427         }
428         if (data.code == 1) { // WARNING
429             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
430             // publish error code and text message on a separate channel for whoever is interested
431             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
432
433             $("#notifications").notify("create", "sticky", {
434               title: 'Warning',
435               text: data.description
436             },{
437               expires: false,
438               speed: 1000
439             });
440             
441         }
442         // once everything is checked we can use the 'value' part of the manifoldresult
443         var result=data.value;
444         if (result) {
445             //if (!!callback /* domid */) {
446             //    /* Directly inform the requestor */
447             //    if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
448             //    callback(result);
449             //    //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
450             //    //jQuery('#' + domid).trigger('results', [result]);
451             //} else {
452                 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
453                 /* query is the query we sent to the backend; we need to find the
454                  * corresponding analyezd_query in manifold.all_queries
455                  */
456
457                 // XXX We might need to update the corresponding update_query here 
458                 query_ext = manifold.query_store.find_query_ext(query.query_uuid);
459                 query = query_ext.query;
460
461                 // We don't prepare an update query if the result has more than 1 entry
462                 if (result.length == 1) {
463                     var res = result[0];
464
465                     console.log("Locating update query for updating params", update_query);
466                     update_query_ext = query_ext.update_query_ext;
467                     update_query = update_query_ext.query;
468
469                     // Testing whether the result has subqueries (one level deep only)
470                     // iif the query has subqueries
471                     var count = 0;
472                     var obj = query.analyzed_query.subqueries;
473                     for (method in obj) {
474                         if (obj.hasOwnProperty(method)) {
475                             var key = manifold.metadata.get_key(method);
476                             if (!key)
477                                 continue;
478                             if (key.length > 1)
479                                 continue;
480                             key = key[0];
481                             var sq_keys = [];
482                             var records = res[method];
483                             if (!records)
484                                 continue
485                             $.each(records, function (i, obj) {
486                                 sq_keys.push(obj[key]);
487                             });
488                             update_query.params[method] = sq_keys;
489                             count++;
490                         }
491                     }
492
493                     if (count > 0) {
494                         update_query_ext.disabled = false;
495                     }
496
497                 }
498
499
500                 
501                 // We have results from the main query
502                 // inspect subqueries and get the key for each
503
504                 // XXX note that we might need the name for each relation, but
505                 // this might be for SET_ADD, since we need to recursively find
506                 // the path from the main query
507
508
509                 tmp_query = manifold.find_query(query.query_uuid);
510                 manifold.publish_result_rec(tmp_query.analyzed_query, result);
511             //}
512
513         }
514     },
515
516     /************************************************************************** 
517      * Plugin API helpers
518      **************************************************************************/ 
519
520     raise_event_handler: function(type, query_uuid, event_type, value)
521     {
522         if ((type != 'query') && (type != 'record'))
523             throw 'Incorrect type for manifold.raise_event()';
524
525         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
526
527         $.each(channels, function(i, channel) {
528             if (value === undefined)
529                 $('.plugin').trigger(channel, [event_type]);
530             else
531                 $('.plugin').trigger(channel, [event_type, value]);
532         });
533     },
534
535     raise_query_event: function(query_uuid, event_type, value)
536     {
537         manifold.raise_event_handler('query', query_uuid, event_type, value);
538     },
539
540     raise_record_event: function(query_uuid, event_type, value)
541     {
542         manifold.raise_event_handler('record', query_uuid, event_type, value);
543     },
544
545
546     raise_event: function(query_uuid, event_type, value)
547     {
548         // Query uuid has been updated with the key of a new element
549         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
550         query = query_ext.query;
551
552         switch(event_type) {
553             case FIELD_STATE_CHANGED:
554                 // value is an object (request, key, value, status)
555                 // update is only possible is the query is not pending, etc
556                 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
557                 // we should map SET_ADD on this...
558
559                 // 1. Update internal query store about the change in status
560
561                 // 2. Update the update query
562                 update_query = query_ext.main_query_ext.update_query_ext.query;
563                 update_query.params[value.key].push(value.value);
564
565                 // 3. Inform others about the change
566                 // a) the main query...
567                 manifold.raise_record_event(query_uuid, event_type, value);
568
569                 // b) subqueries eventually (dot in the key)
570                 // XXX make this DOT a global variable... could be '/'
571                 break;
572
573             case SET_ADD:
574             case SET_REMOVED:
575     
576                 // update is only possible is the query is not pending, etc
577                 // CHECK status !
578
579                 // XXX we can only update subqueries of the main query. Check !
580                 // assert query_ext.parent_query == query_ext.main_query
581                 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
582
583                 // This SET_ADD is called on a subquery, so we have to
584                 // recontruct the path of the key in the main_query
585                 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
586
587                 var path = "";
588                 var sq = query_ext;
589                 while (sq.parent_query_ext) {
590                     if (path != "")
591                         path = '.' + path;
592                     path = sq.query.object + path;
593                     sq = sq.parent_query_ext;
594                 }
595
596                 main_query = query_ext.main_query_ext.query;
597                 data = {
598                     request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
599                     key   : path,
600                     value : value,
601                     status: FIELD_REQUEST_PENDING,
602                 };
603                 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
604
605                 // old //update_query.params[path].push(value);
606                 // old // console.log('Updated query params', update_query);
607                 // NOTE: update might modify the fields in Get
608                 // NOTE : we have to modify all child queries
609                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
610
611                 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
612                 // object = the same as get
613                 // filter = key : update a single object for now
614                 // fields = the same as get
615                 manifold.raise_query_event(query_uuid, event_type, value);
616
617                 break;
618
619             case RUN_UPDATE:
620                 update_query = query_ext.main_query_ext.update_query_ext.query;
621                 
622                 manifold.asynchroneous_exec ( [ {'query_uuid': update_query.query_uuid, 'publish_uuid' : query_uuid} ], false);
623                 break;
624
625             case FILTER_ADDED:
626                 manifold.raise_query_event(query_uuid, event_type, value);
627                 break;
628             case FILTER_REMOVED:
629                 manifold.raise_query_event(query_uuid, event_type, value);
630                 break;
631             case FIELD_ADDED:
632                 main_query = query_ext.main_query_ext.query;
633                 main_update_query = query_ext.main_query_ext.update_query;
634                 query.select(value);
635
636                 // Here we need the full path through all subqueries
637                 path = ""
638                 // XXX We might need the query name in the QueryExt structure
639                 main_query.select(value);
640
641                 // XXX When is an update query associated ?
642                 // XXX main_update_query.select(value);
643
644                 manifold.raise_query_event(query_uuid, event_type, value);
645                 break;
646
647             case FIELD_REMOVED:
648                 query = query_ext.query;
649                 main_query = query_ext.main_query_ext.query;
650                 main_update_query = query_ext.main_query_ext.update_query;
651                 query.unselect(value);
652                 main_query.unselect(value);
653
654                 // We need to inform about changes in these queries to the respective plugins
655                 // Note: query & main_query have the same UUID
656                 manifold.raise_query_event(query_uuid, event_type, value);
657                 break;
658         }
659         // We need to inform about changes in these queries to the respective plugins
660         // Note: query, main_query & update_query have the same UUID
661         manifold.raise_query_event(query_uuid, event_type, value);
662         // We are targeting the same object with get and update
663         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
664         // NOTE: Editing a subquery == editing a local view on the destination
665
666         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
667         // For the time being, we will collect all columns during the first query
668     },
669
670     /* Publish/subscribe channels for internal use */
671     get_channel: function(type, query_uuid) 
672     {
673         if ((type !== 'query') && (type != 'record'))
674             return null;
675         return '/' + type + '/' + query_uuid;
676     },
677
678 }; // manifold object
679 /* ------------------------------------------------------------ */
680
681 (function($) {
682
683     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
684     // https://gist.github.com/661855
685     var o = $({});
686     $.subscribe = function( channel, selector, data, fn) {
687       /* borrowed from jQuery */
688       if ( data == null && fn == null ) {
689           // ( channel, fn )
690           fn = selector;
691           data = selector = undefined;
692       } else if ( fn == null ) {
693           if ( typeof selector === "string" ) {
694               // ( channel, selector, fn )
695               fn = data;
696               data = undefined;
697           } else {
698               // ( channel, data, fn )
699               fn = data;
700               data = selector;
701               selector = undefined;
702           }
703       }
704       /* </ugly> */
705   
706       /* We use an indirection function that will clone the object passed in
707        * parameter to the subscribe callback 
708        * 
709        * FIXME currently we only clone query objects which are the only ones
710        * supported and editable, we might have the same issue with results but
711        * the page load time will be severely affected...
712        */
713       o.on.apply(o, [channel, selector, data, function() { 
714           for(i = 1; i < arguments.length; i++) {
715               if ( arguments[i].constructor.name == 'ManifoldQuery' )
716                   arguments[i] = arguments[i].clone();
717           }
718           fn.apply(o, arguments);
719       }]);
720     };
721   
722     $.unsubscribe = function() {
723       o.off.apply(o, arguments);
724     };
725   
726     $.publish = function() {
727       o.trigger.apply(o, arguments);
728     };
729   
730 }(jQuery));
731
732 /* ------------------------------------------------------------ */
733
734 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
735 //make sure to expose csrf in our outcoming ajax/post requests
736 $.ajaxSetup({ 
737      beforeSend: function(xhr, settings) {
738          function getCookie(name) {
739              var cookieValue = null;
740              if (document.cookie && document.cookie != '') {
741                  var cookies = document.cookie.split(';');
742                  for (var i = 0; i < cookies.length; i++) {
743                      var cookie = jQuery.trim(cookies[i]);
744                      // Does this cookie string begin with the name we want?
745                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
746                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
747                      break;
748                  }
749              }
750          }
751          return cookieValue;
752          }
753          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
754              // Only send the token to relative URLs i.e. locally.
755              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
756          }
757      } 
758 });
759