Reputation: 278
I've been trying to work and understand ajax without relying on jquery for learning purposes.
I'm sending data I got from a textfield.
Here's my ajax
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('id_tags').onkeyup = () => {
// initialize new request
const request = new XMLHttpRequest();
request.open("POST", "{% url 'tag_suggestions' %}");
var keyword = document.getElementById('id_tags').value;
data = {"keyword": keyword};
//when request is finished
request.onload = () => {
console.log("Test");
}
//send request
request.setRequestHeader("X-CSRFToken", '{{csrf_token}}');
request.send(JSON.stringify(data));
};
});
Here's the django function that listens on my ajax requests
def tag_suggestions(request):
print('inside tag_suggestions ')
if request.method == 'POST':
print(request.POST.keys())
return ('Test')
else:
print('not ajax Test')
return HttpResponse('Test')
I've tested my javascript code it's just fine. It listens on events, got the value properly.
But in my django, when it executes request.POST.keys()
, the output will be
dict_keys([])
and I concluded that I'm not receiving the data from my ajax request.
Upvotes: 0
Views: 576
Reputation: 106
As it was mentioned, you can access your POST data as follows:
data = json.loads(request.body)
I think you'd also need to set a Content-Type
header in your JS Ajax for it to work though:
request.setRequestHeader("Content-Type", 'application/json;');
P.S. Feels more like a comment, but I can't comment for now.
Upvotes: 2
Reputation: 412
The data of your post as Json should be load by the json model.
def tag_suggestions(request):
print('inside tag_suggestions ')
if request.method == 'POST':
data = json.loads(request.body)
print(data)
return ('Test')
else:
print('not ajax Test')
return HttpResponse('Test')
Upvotes: 0
Reputation: 292
You need to init the ajax
call
$.ajax({
url: 'your url',
method: 'POST',
data: {"keyword": keyword},
success: function(response) {
# response is the data what is returned from the view, in
# your case, from tag_suggestions
}
});
And on django
side, you need to return a json_response
not a httpResponse
And of course, check if the request is ajax
. Don't remember the correct
syntax, but something like
if request.is_ajax
Maybe you will need additional checking based on request type
Upvotes: 0