Reputation: 2570
I have a login form with an <a>
element that I want to make a post request with. When I'm debugging the backend Django code it doesn't see the request method as a POST but rather as a GET.
HTML
<form id="login">
{% csrf_token %}
{{login_form.as_p}}
<a id="post" href="">post</a>
</form>
JavaScript
$('document').ready(function(){
$('a#post').click(function(){
$.ajax({
type: 'POST',
url: '#',
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
dataType: 'json',
success: function(data){
console.log(data);
}
})
})
})
Why is this?
Upvotes: 0
Views: 37
Reputation: 318372
You have to prevent the default action of the anchor, which will just reload the page when the href
attribute is empty
$(document).ready(function(){
$('#post').on('click', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : window.location.href,
data : {csrfmiddlewaretoken: '{{ csrf_token }}' },
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
});
Upvotes: 1