I am able to have the browser send the server the initial http post, and from the server I am able to send the browser the json which contains the json represented objects. But from here I am not able to populate the select options.
We'll actually I am but it is only one level deep, and also for some season add it all into one option (least of my worries atm). It places this within the select option, if the data variable contains objects
"[object, Object], [object, Object], [object, Object]"
View Code
if request.is_ajax():
selected_date = request.POST['selected_date']
slots_on_day = Calendar.objects.filter(date=selected_date)
data = []
for cal in slots_on_day:
data.append(model_to_dict(cal))
return JsonResponse(status=200, data={'slots_on_day': data})
json structure (data variable)
[{'id': 47,
'date': datetime.date(2018, 3, 12),
'timeslot_A': datetime.time(10, 0),
'timeslot_B': datetime.time(12, 0),
'booked': True},
{'id': 45,
'date': datetime.date(2018, 3, 12),
'timeslot_A': datetime.time(8, 0),
'timeslot_B': datetime.time(10, 0),
'booked': False}]
The Ajax Success
success: function(data){
$.each(data, function(key, value){
$('select[name=slot]').append('<option value="' + key + '">' + value2 +'</option>');
});
}
Here is something else I tried
success: function(data){
$.each(data, function(key, value){
for (var key in data) {
$('select[name=slot]').append('<option value="' + key + '">' + value +'</option>');
}
EDITED - Heres Templates
<div class="col-6">
<span>Date:</span>
<input type="text" name="day" id="datepicker" readonly="readonly" required />
</div>
<div class="col-6">
<span>Time:</span>
<div class="input-select">
<select name="slot" id="display_slots" required>
<option value="" selected>---------</option>
</select>
</div>
</div>
UPDATE
Now for the ajax success I have this:
success: function(data){
$.each(data['slots_on_day'], function(key, value){
$('select[name=slot]').append('<option value="' + key + '">' + value +'</option>');
});
}
now what this does is it adds a value to each of the appended objects starting at 0 and incriminating by 1. So the first option will have a value of 0. The second a value of 1 etc.
The text for each of these is always '[object Object]'
The console.log(data) output is:
{
"slots_on_day": [
{
"id": 41,
"date": "2018-03-05",
"timeslot_A": "08:00:00",
"timeslot_B": "10:00:00",
"booked": false
},
{
"id": 42,
"date": "2018-03-05",
"timeslot_A": "08:00:00",
"timeslot_B": "10:00:00",
"booked": true
},
{
"id": 43,
"date": "2018-03-05",
"timeslot_A": "10:00:00",
"timeslot_B": "12:00:00",
"booked": false
},
{
"id": 44,
"date": "2018-03-05",
"timeslot_A": "10:00:00",
"timeslot_B": "12:00:00",
"booked": false
}
]
}