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)}
                }
        }
    });


  }

 

AJAX Call for uploading file with POST

upload.html

<script>
    var csrftoken = $("[name=csrfmiddlewaretoken]").val();
    var zdocid = document.getElementById('id_doc_extno').value;
    var zpath1 =''
    function saveFile() {
        $.ajax({
            url: '/ajax/fileupload/' + zdocid + '/', 
            type: 'POST',
            headers:{
                "X-CSRFToken": csrftoken
            },
            data: new FormData($('#zupload')[0]),
            cache: true,
            processData: false,
            contentType: false                    // Using FormData, no need to process data.
            }).done(function(zpath){
            console.log("Success: Files sent!");
            zlink = '<a href=' + zpath + '>' + zpath + "</a><br/>";
            $('#zattach_list').append(zlink);
            //alert(zpath);
            }).fail(function(){
            console.log("An error occurred, the files couldn't be sent!");
        });


    }

</script>


Views.py

def ajax_uploadfile(data= '',zdocid=''):
    attch_file = 'C:/Users/uploads/' + data.FILES['file'].name 
    obj = Attachment_lib()
    f = data.FILES['file']
    with open(attch_file, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    attch_data = ''
    with open(attch_file, 'rb') as f:
        attch_data = f.read()
    obj.attach_data = attch_data
    obj.attach_date =  datetime.now()
    obj.attach_parent_extno = zdocid
    obj.attach_path = '/uploads/' + data.FILES['file'].name 
    obj.save() 
    #os.remove(attch_file)
    print('success')
    return HttpResponse('/uploads/' + data.FILES['file'].name )

 

            Related
AJAX Call : Django Javascript