arnab saha
arnab saha

Reputation: 17

In django how to send json object using XMLHttpRequest in javascript

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

Upvotes: 1

Views: 2697

Answers (1)

Uday Kiran
Uday Kiran

Reputation: 229

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.

Upvotes: 1

Related Questions