I'm creating a dropdown list select with ajax and Jquery in Django The expected behavior is when I choose the first select, the ajax will fill the second one This is what I have for while:
models.py
class MaintenanceEquipment(models.Model):
equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True)
line_nm = models.CharField(max_length=20, blank=True, null = True)
sequence = models.CharField(max_length=30, blank=True, null = True)
equip_model = models.CharField(max_length=30, blank=True, null = True)
def __str__(self):
return self.equip_id
views.py:
def maintenanceIssueView(request):
equipment_list = MaintenanceEquipment.objects.all()
context = {'equipment_list':equipment_list}
return render(request, 'maintenance/maintenanceIssue.html', context)
def load_equipment(request):
from django.core import serializers
if request.method == 'GET':
line_nm = request.GET.get('line_nm')
equipment = MaintenanceEquipment.objects.filter(line_nm=line_nm)
instances = serializers.serialize('json', equipment)
print(instances)
return HttpResponse(instances, content_type='application/json')
urls.py:
urlpatterns = [
path('maintenanceIssueView/', views.maintenanceIssueView, name="maintenanceIssueView"),
path('ajax/load_equipment/', views.load_equipment, name="ajax_load_equipment"),
]
maintenanceIssue.html:
<form method="POST" id="maintenanceForm" data-equipment-url="{% url 'ajax_load_equipment' %}" novalidate>
{% csrf_token %}
<div style="text-align:left;" class="container-fluid">
<div style="text-align:left;" class="form-row">
<div class="form-group col-md-6">
<label for="line_nm" style="font-size:medium;">Line</label>
<select class="form-control" id="line_nm" name="line_nm" >
{% for instance in equipment_list %}
<option id="{{ instance.line_nm }}" value="{{ instance.line_nm }}">{{ instance.line_nm }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-6">
<label for="sequence" style="font-size:medium;">Machine</label>
<select class="form-control" id="sequence" name="sequence"></select>
</div>
</div>
</div>
</form>
<script>
$("#line_nm").change(function () {
var url = $("#maintenanceForm").attr("data-equipment-url");
var line_nm = $(this).val();
$.ajax({
url: url,
data: {
'line_nm': line_nm
},
success: function (response) {
// this function executes on receiving a successful response from the backend:
var secondSelect = $('#sequence');
secondSelect.empty();
for (var instance in response.instances) {
secondSelect.append($('<option>', {
value : instance.sequence,
text : instance.sequence
}));
}
}
});
});
</script>
The problem is: When I print the output of my view in the terminal, I have:
[{"model": "maintenance.maintenanceequipment", "pk": 4,
"fields":
{"equip_id": "Q230-095504-003", "mfg_part_code": "P12122", "line_nm":
"PBA-02", "sequence": "LOADER", "equip_model": "FML-400BAI-HE-SV"}},
{"model": "maintenance.maintenanceequipment", "pk": 5,
"fields":
{"equip_id": "Q230-108839-001", "mfg_part_code": "P12122", "line_nm":
"PBA-02", "sequence": "C-MOUNTER1", "equip_model": "MAI-H8"}}]
How to recover it in my ajax to fill the second select? The only data I need is the "fields": sequence
Expected value: LOADER, C-MOUNTER1
The value that is current appering in select is: 0, 1, 2, 3, 4, 5, 6, 7 .... Maybe a string count
I appreciate if someone can help
CodePudding user response:
You need parse JSON response which you get from server then loop through JSON Array and get the sequence value using response["instances"][i]["fields"]["sequence"] .
Demo Code:
//this is for demo ....
var response = {
"instances": [{
"model": "maintenance.maintenanceequipment",
"pk": 4,
"fields": {
"equip_id": "Q230-095504-003",
"mfg_part_code": "P12122",
"line_nm": "PBA-02",
"sequence": "LOADER",
"equip_model": "FML-400BAI-HE-SV"
}
},
{
"model": "maintenance.maintenanceequipment",
"pk": 5,
"fields": {
"equip_id": "Q230-108839-001",
"mfg_part_code": "P12122",
"line_nm": "PBA-02",
"sequence": "C-MOUNTER1",
"equip_model": "MAI-H8"
}
}
]
}
/*$("#line_nm").change(function () {
var url = $("#maintenanceForm").attr("data-equipment-url");
var line_nm = $(this).val();
$.ajax({
url: url,
data: {
'line_nm': line_nm
},
dataType :'json', //add this....///
success: function (response) { */
var secondSelect = $('#sequence');
secondSelect.empty();
//loop thorugh json response //is its json object > json array use : response.instances
for (var i = 0; i < response.instances.length; i ) {
secondSelect.append($('<option>', {
value: response["instances"][i]["fields"]["sequence"], //get the sequence
text: response["instances"][i]["fields"]["sequence"]
}));
}
/*}
});
});*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select class="form-control" id="sequence" name="sequence"></select>
CodePudding user response:
If you only need the sequence field, you can just get this field with Django
equipment = MaintenanceEquipment.objects.filter(line_nm=line_nm)
equipment_sequences = [e.sequence for e in equipment]