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>
wordpkmany times on the page?