1👍
Luca’s answer should solve your problem. I’d like to share how I normally implement AJAX POST requests. I write the jQuery code inside the template(html) file.
I know this isn’t the best practice but doing so allows me to
-
Use the
{% url %}
tag instead of hard coding the url in the js file. -
Use
{{ csrf_token }}
instead of fetching the value from the
hidden input field.
Normally, I have a block called extrajs in my base.html file (the one which I extend on every single template) .
Now whenever i need to include AJAX functionality this is how i do it
{% block extrajs %}
<script>
...
$.ajax({
...
url:'{% url "app_name.views.func_name" %}',
data:{ ... ,'csrfmiddlewaretoken':'{{ csrf_token }}', ... },
...
});
</script>
{% endblock %}
0👍
My suggestion is that you should make sure the csrf token keyword is inline with the middleware handling it (in your ajax it’s csrtoken
). In my django app, the token is called csrfmiddlewaretoken
.
The ajax post request should look like the following:
$.ajax({
type:"POST",
url: "http://127.0.0.1:8000/search/",
data:{'search_text':cadena,
'csrfmiddlewaretoken' : csrf},
success:function(respuesta){
$('#search-results').html(respuesta);
}