I want to pass data from an AJAX call to my django view.
My html:
<a href="javascript:" class="word_known btn btn-warning btn-sm" data-songpk="{{song_pk}}" data-userpk="{{user_pk}}">Yes</a>
My jquery:
$(document).ready(function() {
var known_words = 0;
$(".word_known").click(function() {
known_words++;
var reference = this;
var songpk = $(this).data('songpk');
var userpk = $(this).data('userpk');
$.ajax({
url: "/videos/songs/vocab/"+songpk+"/"+userpk+"/",
data: {known_words: known_words},
success: function(result) {
$(reference).removeClass("btn-warning");
$(reference).addClass("btn-success");
$(reference).text("Known");
},
failure: function(data) {
alert("There is an error!")
}
})
});
})
My view:
def word_known(request):
if request.method =='POST':
pass
elif request.method == 'GET':
request.GET.get('known_words')
known_words = request.session.get('known_words')
return known_words
My url for my videos
app:
path('songs/vocab/<int:pk_song>/<int:pk_user>/known_words=<int:count>', views.word_known, name='song-known'),
The known_words
variable seems to be working (when I click the count goes up), but I get a 404 error. The following url is displayed: GET http://dev-lr:8000/videos/songs/vocab/1/3/?known_words=1 404 (Not Found)
.
Can anybody please tell me what I am doing wrong?
2
Answers
Turns out my problem was that I missed a forward slash in my url path, and I also didn't include all the necessary arguments.
So I changed my view like this:
And my url like this:
And now it is working.
From your code, it seems that your view’s path is configured differently than the one you are calling in the frontend. See that you are missing the initial
?
for the query string in the path, and hence the 404. I would suggest that instead of hardcoding the URL by code, you should use the{% url %}
template tag, likeYou can do the same in the rest of your Javascript code, think that the Django templating occurs before the page is served, so you can use your template variables in that part without problem, like:
and then you avoid the need to fetch the value from the HTML element.
Another thing that seems weird to me in the code is the way you are handling things (using a GET request to submit some kind of data), but that is another story for another question 🙂