Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving POST data from jQuery in Django without a form

I am currently able to use the post method of jQuery to a view pointed by myurl

 jQuery.post("/myurl", {'value1':value1, 'value2':value2,
                        'csrftoken': '{{ csrf_token }}'}, 
             function(data) {
                        alert("Data Loaded: " + data);
                            });

However, I don't know how to retrieve the posted data inside the view without using a form:

 def save_user_graph(request):
      if request.method == 'POST': 
            return HttpResponse(request.POST.get('value1'),status=201)

returns None.

like image 262
Mermoz Avatar asked Dec 19 '25 13:12

Mermoz


1 Answers

If save_user_graph is returning None, then request.method is not POST. If save_user_graph is returning an HttpResponse with the word 'None' in it, then value1 isn't being sent correctly. Can you clarify which is the case?

If you have chrome, try navigating to the page with the developer toolbar open. You can go to the 'console' tab and view the AJAX request and see what data was sent with it, to make sure that the data was sent correctly.

Similarly, if you have firefox and firebug, you can go to the page and watch the ajax request and check the post parameters.

Assuming that the javascript works, you'll want to log request.POST in save_user_graph. In a pinch, you can just print request.POST and, assuming you're using the django dev server, the output will be printed in the dev server output.

We'll need a bit more debugging info before we can give a better answer. :)

like image 53
So8res Avatar answered Dec 21 '25 10:12

So8res



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!