1

Please Help me with how to send json object and receive it it views.py in django.

my script:

var obj={ 'search_name':search_name,'search_email':search_email };
jsonobj=JSON.stringify(obj);
//alert(jsonobj);
var xhr=new XMLHttpRequest();
xhr.open('POST',"viewprofile",true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(jsonobj);
arnab saha
  • 17
  • 6
  • welcome to SO, can you check this question, may be this is a duplicate. https://stackoverflow.com/questions/24068576/how-to-receive-json-data-using-http-post-request-in-django-1-6 – ytsejam Jun 07 '20 at 09:05
  • i tried, var headers = {'content-type': 'application/json'} var r=xhr.post("viewprofile", data=json.dumps(jsonobj), headers=headers), its giving json not defined error in this-> json.dumps(jsonobj) .... is this supposed to be JSON instead ? – arnab saha Jun 07 '20 at 10:13

1 Answers1

1

Using XMLHttpRequest() in plain JavaScript.

XMLHttpRequest is an API that provides client functionality for transferring data between a client and a server.

xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () { 
    if (xhr.readyState == 4 && xhr.status == 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.name)
    }
}
var data = JSON.stringify({"email":"tomb@raider.com","name":"LaraCroft"});
xhr.send(data);

Using AJAX Calls (preferred way)

    $.ajax({
        url: "https://youknowit.com/api/",
        type: "POST",
        data: { apiKey: "23462", method: "POST", ip: "208.74.35.5" },
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });

Note: Keeping an eye on developer tools or firebug XHR debug process is good way to learn more about the api calls be it in any technology.

Uday Kiran
  • 229
  • 2
  • 13
  • the above one i have tried but its giving an error:Forbidden (CSRF token missing or incorrect.): /viewprofile [07/Jun/2020 15:22:46] "POST /viewprofile HTTP/1.1" 403 2513 – arnab saha Jun 07 '20 at 09:53
  • There are two methods for it , i will tell the easier one , `from django.views.decorators.csrf import csrf_exempt` and add a decorator to the function which ajax is calling like this `@csrf_exempt def upload(request, no):` – Uday Kiran Jun 07 '20 at 10:41