0

I have dictionary in javascript something like this:

var data = {"name":"nitin raturi"}

Now I want this data to be accessed in my django view something like this:

def my_view(request):
    data = request.POST

How to send data to my url using jquery?

Nitin Raturi
  • 1,505
  • 1
  • 7
  • 12

1 Answers1

1

lets do this.

This is your dictionary in javascript:

var data = {"name":"nitin raturi"};

Now define a function that will make a post request using jquery.

function send_data(data, callback) {
// callback is a function that you should pass to handle your response
$.ajax({
    type: "POST",
    url: '/sample-url/', // change this to your url here
    data: {"data": JSON.stringify(data)},
    success: function (response) {
        callback(response);
    },
});

}

Now use the send_data function like this:

send_data(data,function(response){
//handle your response here
console.log(response);

})

Now you can access your data in your django view like this:

import json

@csrf_exempt
def my_view(request):
    data = request.POST.get('data')
    data = json.loads(data) # this will convert your json data to python dictionary
    name = data.get("name")
    // Handle your data and return anything you wish
    return render(request,"index.html",{})
Nitin Raturi
  • 1,505
  • 1
  • 7
  • 12
  • This problem already had an answer [here](https://stackoverflow.com/questions/12744159/django-jquery-post-request) why do you post and answer it again within a few seconds ? – Linh Nguyen Dec 03 '19 at 08:03
  • I did not find for simple views, and one full solution instead of in parts. – Nitin Raturi Dec 03 '19 at 08:17
  • It's not about the view it's about your question of getting POST data in django view, as any view in django you can just get the POST data from `request.POST.get()` – Linh Nguyen Dec 03 '19 at 08:21