Paras Botadra
Paras Botadra

Reputation: 23

How to get and access JSON data from ajax in django view?

I am trying to send dynamically created JSON data from my template using ajax call to the view. I am able to generate and pass the JSON data via ajax call but unable to read the same in the view. I read lots of articles and stackoverflow post regarding this but nothing worked for this simple task. Below is my Ajax call:

$(document).ready(function() {
    $('#applybtn').click(function(){
        var selectedpackages = [];
        {% for package in packages %}
            if($("input[name=package{{forloop.counter}}]").is(':checked')){
                type = $("input[name=package{{forloop.counter}}]:checked").attr('id');
                var Obj = {}
                Obj['pkgid'] = {{package.id}};
                Obj['type'] = type;
                selectedpackages.push(Obj);
            }
        {% endfor %}
        var mystring = JSON.stringify(selectedpackages);
        $.ajax({
            url:"/ApplyCode/",
            type:"GET",
            data:mystring,
            dataType: "json",
            contentType: "application/json",
            success: function(data){
                alert(data);
            }
        });    
    });
});

In above given code, you can ignore the for loop part as it is just looping through some packages and checking that which package is selected by users on that page and accordingly generating a dictionary to pass as JSON object. Also, I checked the data generated in mystring variable (using alert(mystring);) before sending it to view and it was having the desired data.

Below is the code for my view:

import json

def applycode(request):
    context=RequestContext(request)
    pkgid=""
    if request.method=='GET':
        selectedpackages = json.loads(request.body)
    else:
        pass
    return HttpResponse(selectedpackages)

I am sure I am missing something over here while getting the JSON data in "selectedpackages" variable. I tried lots of other ways as well but nothing worked. Here I just want to get the data and than wants to access each element of the same. Any help is appreciated.

Upvotes: 0

Views: 4048

Answers (1)

solarissmoke
solarissmoke

Reputation: 31514

request.body will not have anything in it if you do a GET request, which will put everything in the URL itself. You need to change your AJAX call to do a POST:

$.ajax({
    // ...
    type:"POST",
    // ...
});

and then modify your view code accordingly:

if request.method == 'POST':
    selectedpackages = json.loads(request.body)

Upvotes: 5

Related Questions