Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 510
Amritha Menon Avatar asked Feb 14 '18 18:02

Amritha Menon


People also ask

How get data from AJAX to Django?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

How does AJAX save data in Django?

Create the AJAX View First, we set up an if statement to check if the request is a POST request. If it is a POST request, we pass the posted data stored in request. POST to the form—this is known as binding a form to a dataset. Next, we check the form to see if the submitted data is valid.

Can you use AJAX with Django?

when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template. If you don't think Ajax is the best practice.


1 Answers

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'),
]
like image 139
abybaddi009 Avatar answered Oct 21 '22 23:10

abybaddi009