I keep receiving ‘Not Ajax’ as a response during my form submission. I have to be missing something small but I cannot see it…
class VideoLikeView(View):
def post(self, request):
if request.is_ajax():
message = 'Ajax'
else:
message = 'Not Ajax'
return HttpResponse(message)
The AJAX code looks like this:
$(function () {
$("#like-form").submit(function (event) {
$.ajax({
type: "POST",
url: form.attr('action'),
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {'pk': $(this).attr('value')},
success: function(response) {
alert('Video liked');
},
error: function(rs, e) {
alert(rs.responseText);
}
}
});
});
});
And my HTML:
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}">
<button type="submit">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
</form>
One question to add to this; how can I use an <input>
in my form without using a <button>
? I would like to use fontawesome icons but it seems I have to use a button to get the form to submit.
2
Answers
I found one answer on the internet that seems to work but I don't understand what the issue was. Seems like some type of serialization needed (?)... Anyways, here is what worked:
Would love to hear from people why this works and not the previous..
try change your btn type button and add ID for event click :
since putting the submit button goes directly to view.py without going through AJAX
in your script
and your view.py