in your template, open a js block
{% block javascript %}
<script>
function test() {
//get some val form dom element
var val1 = $('#test_select').val();
$.ajax({
url: "{% url 'url:example'%}",
data: {
'test_val': val1,
},
dataType : 'json',
success: function(data){
if (data){
console.log("all right")
}else{
alert('error');
}
}
});
};
{% endblock%}
you can specify a post request with type: "POST", between dataType and data and sending csrf_token in data with 'csrfmiddlewaretoken': '{{ csrf_token }}',
on django, write the view that match with the url in the ajax function, there are multiple ways to return the value you want depending on the operation that you perform.
for example:
def Names(request):
#recibe post values
if request.method == "POST":
test_val
= request.POST.get('
test_val
', None)
queryset = TestModel.objects.filter(name=test_val)
return HttpResponse(serializers.serialize("json", queryset))
with this I can update names in an input element, this will be on succes function of ajax call:
success: function(data){
if (data){
$.each(data, function(arrayID,model) {
first_name= model.fields["
first_name
"];
last_name= model.fields["
last_name
"];
$("#first_name
").val(
first_name
);
$("#last_name
").val(
last_name
);
});
}else{
alert('Can't find a match');
}
}
I remember when I was learning about this, I readed about some warnings about sending csrf_token the way i use here, or pass the url in this way, so I really encourage that you can search about this.
Regards.