[Answered ]-Extracting a field value from JsonResponse in Django and pass it to Ajax Jquery

1๐Ÿ‘

โœ…

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>
๐Ÿ‘คSwati

0๐Ÿ‘

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]
๐Ÿ‘คHelge Schneider

Leave a comment