0

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>
3
  • Just show us more code. How are you looping in template. And your table too Commented Jun 10, 2020 at 2:41
  • I think the issue is that the <a/> link gets added to the page after your script. Commented Jun 10, 2020 at 2:44
  • Also, if you have several elements with the same ID, js will never know which one you are referring to. And did you just declared global wordpk many times on the page? Commented Jun 10, 2020 at 2:49

2 Answers 2

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");
            }});
          });
        });
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you for your answer. The click is now working for every button, but I'm getting a 404 error for all of them. I'll post more code...
@MeL It seems to me the problem is your base URL, see my updated answer and see if this will generate the correct one.
Please, post the URL that is fired and the URL that is expected to fire {% url 'vocab:add-custom' word.pk %}
I am still getting a 404 error, even though the url is now what I expect it to be.
|
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
});

2 Comments

Aaah, thanks! So it would be better to use a class for this?
Yes, absolutely. Also, see the second answer to store wordpk for each add_word button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.