skip to Main Content

I am trying to use an AJAX call to send data to my django view, which I then hope to use in another view. When a user clicks on a particular word, known_words must go up by one (this part works). But I also want to know which word the user clicked on (I have access to this in the template: {{item.0}}. And this is the part that I cannot get to work.

The relevant part of my html (this is the last column of my table, the first column contains {{item.0}}):

<a href="javascript:" class="word_known btn btn-warning btn-sm" data-word="{{item.0}}" data-songpk="{{song_pk}}" data-userpk="{{user_pk}}">Yes</a>

My js:

$(document).ready(function() {
  var known_words = 0;
  var clicked_words = [];
  $(".word_known").click(function() {
    known_words++;
    var reference = this;
    var songpk = $(this).data('songpk');
    var userpk = $(this).data('userpk');
    var clicked_words = $(this).data('clicked_words');  //I know this part is wrong, how can I append the word to the list?
    $.ajax({
      url: "/videos/songs/vocab/known/"+songpk+"/"+userpk+"/",
      data: {known_words: known_words, clicked_words: clicked_words},
      success: function(result) {
    $(reference).removeClass("btn-warning");
    $(reference).addClass("btn-success");
    $(reference).text("Known");
  },
      failure: function(data) {
        alert("There is an error!")
      }
      })

});
})

Views:

def word_known(request, pk_song, pk_user):
    if request.method =='POST':
        pass
    elif request.method == 'GET':
        known_words = request.GET.get('known_words', '')
        clicked_words = request.GET.get('clicked_words', '')
        request.session['known_words'] = known_words
        clicked_words = []
        clicked_words.append(request.session['clicked_words'])
        print('The number of known words is {} and clicked words are {}'.format(known_words, clicked_words))

    return HttpResponse(json.dumps(known_words))

In the console, when I click on a word (not ‘hello’), I get the following in the console:
The number of known words is 1 and clicked words are ['hello']

And if I click a second time on a different word:
The number of known words is 2 and clicked words are ['hello']

So the counter is working, but not the word list. How can I fix that?

2

Answers


  1. Chosen as BEST ANSWER

    In addition to @Daniel Butler's answer, I had to change my view as follows:

    clicked_words = request.GET.getlist('clicked_words[]')
    

    Because apparrently when you send a list through jQuery it changes the keyword as well.


  2. I haven’t tested this, but I think you are overwriting the Array instead of adding to it.

    This line

    var clicked_words = $(this).data('clicked_words');
    

    Should be

    clicked_words.push($(this).data('clicked_words'));
    

    This is a link to the documentation on MDN

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search