skip to Main Content

I want a button click to result in my database being updated without a page refresh. I’ve researched this a lot, and it seems a jquery ajax call is the way to go. But it’s not working. I put a check in to see if the click event is working, and the strange thing is that it only works when I click the first button in the table (the table shows all the user’s words with a ‘for loop’). But then I get a 404 error, so it makes me think that my mistake is in my views? Nothing happens when I click the other words – no error, no click event, nothing. But everything works (i.e. the database gets updated) without using jquery, but then of course the page updates every time. By clicking the button the word should automatically get added to the user’s word list without a page refresh. I’m stuck with this, would really appreciate some help, thanks!

So I need to find out: 1) how to get the click event working every time; 2) how to get the url right in js; and 3) how to get my view right.

My template (without jquery):

 <a id="add_word" href="{% url 'vocab:add-custom' word.pk %}" class="btn btn-warning btn-sm">Add</a>

My template (with jquery):

<a id="add_word" href="#" class="btn btn-warning btn-sm">Add</a>
    
      <script type="text/javascript">
        var wordpk = "{{word.pk}}";
      </script>

My url:
 

app_name='vocab'
    
        path("<int:object>/",views.custom_create_word,name="add-custom"),

My view:
   

 def custom_create_word(request, object):
            if request.method == 'POST':
                pass
            if request.method =="GET":
                from .forms import WordForm
                from .models import Word
                word = Word.objects.get(pk=object)
                user = request.user
                target_word = word.target_word
                source_word = word.source_word
                deck_name = "My Words"
                fluency = 0
                Word.objects.create(user=user, target_word=target_word,
                                     source_word=source_word, deck_name=deck_name, fluency=fluency)
            return HttpResponseRedirect(reverse('vocab:dict'))

My js:
 

$(document).ready(function(){
    $("#add_word").click(function() {
      alert('click is working');
      $.ajax({
            url: "/vocab/"+wordpk+"/",
            success: function (result) {
              $("#add_word").html(result);
              alert("it worked");
            }});
          });
        });

UPDATE
My template:

<tbody>
        <tr>
          {% for word in dict_list %}
          <td>{{word.target_word}}</td>
          <td>{{word.source_word}}</td>
          <td>
            <a href="javascript:" class="add-word btn btn-warning btn-sm" data-wordpk="{{word.pk}}">Add</a>
          </td>
        </tr>
        {% endfor %}
        </tbody>

2

Answers


  1. This is my answer for your first question.

    Your click event was working only one time because you are using id, which is unique in the whole document. So, if you add click event on id, then only the first id element will work. But, html is forgiving language so, you won’t see any html error if you use id in document more than once. You can validate and see if your html is fine or not from w3c Validator. Also, see id attributte.

    So, solution is simple. You can use class selector to check for onclick event. Like:

    <a id="add_word" href="{% url 'vocab:add-custom' word.pk %}" class="add_word btn btn-warning btn-sm">Add</a>
    

    Now, you have added add_word in class, I can select all the elements with the same class. In jquery:

    $(".add_word").click(function(e) {
        e.preventDefault();       // To prevent default function of anchor tag
        // Your code
    });
    
    Login or Signup to reply.
  2. Your code has to be something like this:

     <a href="javascript:" class="add_word btn btn-warning btn-sm" data-wordpk="{{word.pk}}">Add</a>
    

    and then

    $(document).ready(function(){
        $(".add_word").click(function() {
          var wordpk = $(this).data('wordpk');
          $.ajax({
                url: "/vokab/"+wordpk,
                success: function (result) {
                  $("#add_word").html(result);
                  alert("it worked");
                }});
              });
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search