I have one view that I'm trying to display data from a few different places to. My thought would be to do this via Ajax since I won't have a way to execute 3 or 4 urls when this page loads.
I'm able to get the data to the page using the Django Rest Framework and I can view the correct data in the console with my ajax request. I just don't know how to get that data into my html template to start displaying it. Normally I would just pass the context through the view but this is uncharted territory.
I think i'm missing something very small with Jquery as I'm pretty new to javascript and Jquery.
views.py
class LoadLaneHistoricalCarriers(APIView):
authentication_classes = ()
permission_classes = ()
def get(self, request, pk):
load = Load.objects.get(pk=pk)
load_state = load.shipper.state
load_equipment_type = load.equipment_type
historical_loads_in_state = Load.objects.filter(shipper__state=load_state)
carriers = CarrierCompany.objects.filter(state=load_state)
historical_carriers = []
historical_loads = []
for load in historical_loads_in_state:
historical_loads.append(load.id)
historical_carriers.append(load.carrier.name)
data = {
'historical_loads': historical_loads,
'historical_carriers': historical_carriers
}
return Response(data)
Template this is a modal in case it matters.
<script>
var endpoint = '/carrier_notifications/load/historical_carriers/400192/data/'
$.ajax({
method: "GET",
url: endpoint,
success: function (data) {
carriers = data.historical_carriers
console.log(carriers) //This works
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
});
</script>
<table class="table table-condensed" id="historicalCarriers">
<thead>
<tr>
<th>Load Number</th>
</tr>
</thead>
<tbody>
{% for carrier in carriers %}
<tr>
<td>
<a href="#">{{ carrier }}</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
You should return your response as Json Object
from django.http import JsonResponse
data = {
'historical_loads': historical_loads,
'historical_carriers': historical_carriers
}
return JsonResponse(data)
jquery 1st Option (No django for loop needed):
var tbody = $("tbody")
$.ajax({
method: "GET",
url: endpoint,
success: function (data) {
carriers = data.historical_carriers
for(var i = 0 ; i < carriers.length ; i++){
html = '<tr><td><a href="#">'+carriers[i]+'</a></td></tr>';
tbody.append(html)
}
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With