1👍
Your selector $('#btnLike')
is not correct, it is looking for a button with id="btnLike"
.
Try this:
<button type="submit" id="btnLike" class="btn btn-info">Like</button>
Please make sure you load jQuery library in your HTML and wrap all your jQuery code into
$(document).ready(function(){
//your code goes here
});
0👍
the problem is with your value for url. remove the ip address. use relative addressing. also put id to your button.
$('#btnLike').on('click', function(event) {
alert('ok');
$.ajax({
type: 'POST',
url: 'backend/website/like', /* for testig */
data: {
csrfmiddlewaretoken: {% csrf_token %},
post_id = $('#post_id').val(),
},
});
});
Button HTML
<form onsubmit="return false">
{% csrf_token %}
<input type="text" name="post_id" value= {{post.pk}} hidden="hidden">
<button type="submit" id="btnLike" class="btn btn-info">Like</button>
</form>
- Django LDAP authn backend: user authenticated but unable to login
- Security using Django 1.10 + AJAX without any HTML form
- How to return JSON Response correctly in joining multiple table in Django
- Regex to accept anything in url django
0👍
For reference: If you’re serializing the form (as per yts’s comment) then you won’t need to explicitly include the csrf_token in your AJAX code. But if you were using just AJAX, then pass in the token like:
csrfmiddlewaretoken: '{{ csrf_token }}',
not
csrfmiddlewaretoken: '{% csrf_token %}',
The template variable {{ csrf_token }}
outputs the token string, eg.
'mytoken123456789'
whereas the tag {% csrf_token %}
outputs a hidden HTML input element:
<input type="hidden" name='csrfmiddlewaretoken' value='mytoken123456789' />
The syntax error you mention in the comment above is because it’s trying to parse this input element rather than the token string.