0

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.

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer. I tried POST method as well but in that I am getting some http error with status code "HTTP/1.0 403 FORBIDDEN" in the browser console. The line I added in urls.py is url(r'^ApplyCode/$', views.applycode, name='applycode'),. Am I missing something over here?
Probably, I got the solution. I need to add from django.views.decorators.csrf import csrf_exempt at top of my views.py and @csrf_exempt above the applycode() function to make it work. Thanks.!
Yes. See also this section of the documentation.
But I am wondering that now I am not getting any error in my browser console but not even the applycode() is functioning in anyway. I am not able to get any response from that function. Do I need to approach different method for the same? I am also refering the documentation given by you to find the solution..!!
@ParasBotadra you need to change if request.method=='GET': in your views to if request.method=='POST':
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.