Merge branch 'master' of github.com:FinalsClub/karmaworld
[oweals/karmaworld.git] / karmaworld / assets / js / lightbox-add-course.js
1 // setup ajax based autocomplete for the school field in the add course lightbox
2 $(function() {
3
4   function setupAjax(){
5     // Assumes variable csrf_token is made available
6     // by embedding document
7     $.ajaxSetup({
8       beforeSend: function(xhr, settings) {
9         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
10           // Only send the token to relative URLs i.e. locally.
11           xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
12         }
13       }
14     });
15   }
16
17   setupAjax();
18
19   $("#str_school").autocomplete({
20     source: function(request, response){
21       $.ajax({
22         url: "{% url 'json_school_list' %}",
23         data: {q: request.term},
24         success: function(data) {
25           console.log(data);
26           if (data['status'] === 'success') {
27             response($.map(data['schools'], function(item) {
28               return {
29                   value: item.name,
30                   real_value: item.id,
31                   label: item.name,
32               };
33             }));
34           } else {
35             // FIXME: do something if school not found
36             $('#create_school_link').show();
37           }
38         },
39         dataType: "json",
40         type: 'POST'
41       });
42     },
43     select: function(event, ui) { 
44       console.log("select func");
45       console.log("id");
46       console.log(ui.item.value);
47       console.log("name");
48       console.log(ui.item.label);
49       // set the school id as the value of the hidden field
50       $('#id_school').val(ui.item.real_value);
51       // set the School name as the textbox field
52       //$('#str_school').val(ui.item.label);
53     },
54     minLength: 3
55   });
56 });