Amritha Menon
Amritha Menon

Reputation: 145

How do I get data from my AJAX Post to my Django View?

This is what My ajax call looks like

$.ajax({
   url:"{% url 'handsontable' %}",     
   data: {'getdata': JSON.stringify(hot.getData())}, 
   dataType: 'json',
   type: 'POST',                                                                                                                                                                                                

   success: function (res, status) {
        alert(res);
        alert(status);
   },
   error: function (res) {
     alert(res.status);                                                                                                                          
   }
});

This is what my django view looks like.

if request.method == 'POST':
    request_getdata = request.POST.get('getdata', 'None') 
    return HttpResponse(request_getdata)  

The alerts in ajax return the data and "success". But my HttpResponse returns "None".

Any idea why it is not passing the data through? Thanks!

Upvotes: 8

Views: 28544

Answers (4)

Chandan
Chandan

Reputation: 742

What you need to do is :

code for ajax call ( in js file) to send the data to the view

jQuery.ajax(
        {
            'url': "url_pattern_in_urls_py_file/",
            'type': 'POST',
            'contentType': 'application/json; charset=UTF-8',
            'data': JSON.stringify({'updated_data':your_data_val}),
            'dataType': 'json',
            'success': function ( return_data ) {
                
                                //success body
                
                              }
        }          
    );

code in django view with respect to above POST ajax call to receive the data

import json

if request.method == 'POST':
   updatedData=json.loads(request.body.decode('UTF-8'))

Upvotes: 3

evuazeze
evuazeze

Reputation: 102

I cannot add comments because I do not yet have up to 50 reputations as demanded by StackOverflow. This is supposed to be a comment under the answer provided by @abybaddi009. He has done a very good job thus far but the answer needs a finishing touch.

In the view request_getdata = request.POST.get('getdata', None) does not work but this does

body = request.body.decode('utf-8')
data = body[3]

request.body.decode('utf-8') returns a string which would look something like getdata=your_data you can then use string manipulation techniques or regex to extract your data.

Upvotes: 5

Amritha Menon
Amritha Menon

Reputation: 145

I added return false; at the end of the ajax request and it worked. I printed out the values in the view instead of using HttpResponse.

Upvotes: 0

abybaddi009
abybaddi009

Reputation: 1104

First off you are trying to POST to a html file

url:"/utility_tool/decisions/solution_options/handsontable.html",

Instead, it should be a url to a view.

Second, the ajax post request should have the csrftoken in it's header and you can set it up like this:

<script type="text/javascript">
// using jQuery get csrftoken from your HTML
    var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            // if not safe, set csrftoken
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    $.ajax({
        url: "{% url 'name of the view from urls.py' %}",
        data: {
            // here getdata should be a string so that
            // in your views.py you can fetch the value using get('getdata')
            'getdata': JSON.stringify(hot.getData())
        },
        dataType: 'json',
        success: function (res, status) {
            alert(res);
            alert(status);
        },
        error: function (res) {
            alert(res.status);                                                                                                                          
        }
    });
</script>

And in your django view:

# views.py
from django.http import JsonResponse
def someView(request):

    if request.method == 'POST':
        # no need to do this
        # request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
        request_getdata = request.POST.get('getdata', None) 
        # make sure that you serialise "request_getdata" 
        return JsonResponse(request_getdata) 

And in your urls:

# urls.py

urlpatterns = [
    # other urls
    path('some/view/', views.someView, name='name of the view in urls.py'),
]

Upvotes: 12

Related Questions