I try to use Select2 API for JQuery, but I’m having issues with displaying the returned results. I want to be able to search the results I’m getting from my Ajax request.
It gives me 0 errors, and I believe I followed the documentation correctly. When I log the returned data from the Ajax I also get the correct data back.
What am I doing wrong that I can’t see the results inside the select2 input field when searching?
This is my Jquery code:
$('.radiocheck2').on("click", function(){
console.log("test");
$('.nummerplaat').select2({
minimumInputLength: 2,
placeholder: 'Nummerplaat',
dataType: 'json',
ajax: {
url:getallnummerplaten,
method: 'GET',
data: function (params) {
return {
q: params.term,
type: 'public' // search term
};
},
beforeSend: function(xhr, settings) {
if(!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
processResults: function (data) {
arrNummerplaten = []
for(i=0; i < data['nummerPlaten'].length; i++){
arrNummerplaten[i] = data['nummerPlaten'][i].nummerPlaat
}
console.log(arrNummerplaten)
return {
results: arrNummerplaten,
};
},
cache: true
}
});
})
This is my Django view to retrieve the data:
class getAllNummerplaten(LoginRequiredMixin, View):
def get(self, request, *args, **kwargs):
nummerPlaten = list(Voertuigen.objects.all().values("nummerPlaat"))
print(nummerPlaten)
nummerPlatenjson = json.dumps(nummerPlaten)
return JsonResponse({'nummerPlaten': nummerPlaten })
And this is my template code:
<!-- TestCode -->
<div style="display:none" id="overzichttankbeurten" class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Manueel toevoegen</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Nummerplaat</th>
<th>Chauffeur</th>
<th>Datum</th>
<th>Uur</th>
<th>Brandstof</th>
<th>Volume</th>
<th>Prijs</th>
<th>Bedrag</th>
<th>Kilometerstand</th>
<th>Acties</th>
</tr>
</thead>
<tbody id="tableplswerk">
<tr>
<td><input class="form-control nummerplaat" placeholder="Nummerplaat" type="text"></td>
<td><input class="form-control" placeholder="Chauffeur" type="text"></td>
<td><input class="form-control" type="date"></td>
<td><input class="form-control" type="time"></td>
<td><input class="form-control" placeholder="Brandstof" type="text"></td>
<td><input class="form-control" placeholder="Volume" type="number"></td>
<td><input class="form-control" placeholder="Prijs" type="number"></td>
<td><input class="form-control" placeholder="Bedrag" type="number"></td>
<td><input class="form-control" placeholder="Kilometerafstand" type="number"></td>
<td>
<a href=""><i class="fas fa-plus"></i></a>
<!--
<a href=""><i class="fa fa-pencil"></i></a>
<a href="#" data-url="" class="deletefactuur" data-toggle="modal" data-target="#dynamic-modal"><i class="fa fa-trash"></i></a>
-->
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>