[Fixed]-Looping over JSONResponse() result from django in jquery

1👍

change your views like this.

added_list=[]
    if request.method=='POST':
            #Post method initiated.

            try:
                for id in allergies:
                   added ={}                  allergy=PatientAllergy(patient=patient,allergy_id=id,addedby=request.user)
                   allergy.save()
                   added[allergy.id]=id
                   added_list.append(added)
            except BaseException as e:
                pass

    return JsonResponse(added_list,safe=False)

and in jquery

$.ajax({
        type: "POST",
        url: "/patient/addallergy/",
        data: postForm,
        dataType : "json",
        cache: "false",
        success: function (result) {

                alert(result.length); //gives undefined, rendering the below line meaningless

                if (result.length>0){

                     alert(JSON.stringify(result))
                    $.each(result,function(index,value){
                        console.log(value);



                       });

                     result.forEach( function (eachObj){
                       for (var key in eachObj) {
                                  alert(key);
                             alert(eachObj[key])
                            }
                       });

                }


        },
        fail: function (result){

        }


    });

Leave a comment