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);
2
  • welcome to SO, can you check this question, may be this is a duplicate. stackoverflow.com/questions/24068576/… Commented Jun 7, 2020 at 9: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 ? Commented Jun 7, 2020 at 10:13

1 Answer 1

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":"[email protected]","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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
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):

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.