AJAX Call : Django Javascript

DJANGO


 

Django View :  Return Multiple JSON Objects

 

# AJAX Call for graph
from django.http import JsonResponse
import json
from django.http import HttpResponse
from datetime import datetime
import time
def ajax_graph(request,gdata):
    znifty50 = [];zday = 0;zniftyit = [];zniftybank = [];zniftypharma=[];zday=[]
    if gdata == 'NIFTY50':
        zdata = NSE_Stock_data.objects.filter(security='Nifty 50')
        for zrec in zdata:
            znifty50.append(zrec.close)
            zd1 = datetime.strptime(zrec.loaddate,'%d/%m/%Y')
            zddate = int(time.mktime(zd1.timetuple())) * 1000
            zday.append(zddate)

        zdata = NSE_Stock_data.objects.filter(security='Nifty IT')
        for zrec in zdata:
            zniftyit.append(zrec.close)

        zdata = NSE_Stock_data.objects.filter(security='Nifty Bank')
        for zrec in zdata:
            zniftybank.append(zrec.close)

        zdata = NSE_Stock_data.objects.filter(security='Nifty Pharma')[:10]
        for zrec in zdata:
            zniftypharma.append(zrec.close)
        
        zjson = json.dumps({'nifty50': znifty50, 'niftyit': zniftyit ,'niftybank': zniftybank,'niftypharma':zniftypharma,'zday':zday})
    return HttpResponse(zjson)
    #return JsonResponse(znifty50,zniftyit,safe=False)

For single JASON object return use

return JsonResponse(znifty50,zniftyit,safe=False)

 

 

Java Script AJAX Call

function drawChart() {
        data = '';
        $.ajax({
        url: '/graph/NIFTY50/',
        data: {
            //'sh_key': 'EBAN-BSART,H_T161,SH'
        },
        dataType: 'json',
        success: function (zreturn) {
            if (zreturn.nifty50) {
                try {
                    var data = zreturn.nifty50;
                    //alert(data);
                    var zdata = new google.visualization.DataTable();
                    // Add columns
                      zdata.addColumn('number', 'Days');
                      zdata.addColumn('number', 'NIFTY 50');
                      zdata.addRows(data.length);
                      for(i=0;i<data.length;i++){
                        zdata.setCell(i,0,i);
                        zdata.setCell(i,1,parseInt(data[i]));
                      }

                          var options = {
                          title: '',
                          curveType: 'function',
                          legend: { position: 'bottom' }
                        };

                        var chart = new google.visualization.LineChart(document.getElementById('curve_chart_NIFTY50'));
                        chart.draw(zdata, options);


                    } catch (err) {alert(err)}
                }
        }
    });


  }

 

            Related
AJAX Call : Django Javascript