Using XMLHttpRequest with Django

More simple configuration of XMLHttprequest using onload handler.

GET request

We used here err_codes.js to describe html error codes.

<script>

function getXHR(){
    var xhr = false;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else { //code for IE6, IE5
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xhr;
}

function GET(req,successHandler,responseFormat,errorHandler){

    // Instantiate XHR
    xhr = getXHR();
    if(!xhr) {
        alert("Ajax is not supported by your browser!");
        return;
    }

    //process response
    xhr.onload = function() {
        if (xhr.status === 200) {
                response = xhr.responseText;
                if(responseFormat == "txt") response = xhr.responseText;
                if(responseFormat == "json") response = JSON.parse(xhr.responseText);
                if (successHandler) successHandler(response);
        }
        else{
                var err_name = err_codes[xhr.status][0];
                var err_state = err_codes[xhr.status][1];
                var fullDescription = err_codes[xhr.status][2];
                if(errorHandler)
                    errorHandler(xhr.status);
                else
                    alert("Error " + xhr.status + " : " + err_name + "\n[" + err_state + " - " + fullDescription+"]");
        }
    }

    xhr.onerror = function() {
        alert("Error: No response from server.");
    }

    // Send data to server
    xhr.open('GET', req);
    xhr.send(null);
}



function GetData1(){
    var div1 = document.getElementById("div1");
    function success(response){
        div1.innerHTML = response;
    }
    GET("reply2",success,"txt");
}

function GetData2(){
    var div1 = document.getElementById("div1");
    function success(response){
        var key1 = response['key1'];
        var key2 = response['key2'];
        div1.innerHTML = "We get key1 = " + key1 + " and key2 = " + key2;
    }
    GET("reply2",success,"json");
}

window.onload=function(){
    var button1 = document.getElementById('test1_1');
    button1.onclick = GetData1;
    var button1 = document.getElementById('test1_2');
    button1.onclick = GetData2;
}

</script>

<html>

    Server response:<div id="div1" style="height:1.5em; width:100%; border: 1px solid black;"></div>
    <p>
    <button id="test1_1" type="button" >GET text</button>
    <button id="test1_2" type="button" >GET json</button>
    </p>

</html>
Server response:

POST request

<script>

function POST(req,params,successHandler,responseFormat,errorHandler){
    // Instantiate XHR
    xhr = getXHR();
    if(!xhr) {
        alert("Ajax is not supported by your browser!");
        return;
    }
    xhr.onload = function() {
        if (xhr.status === 200) {
                response = xhr.responseText;
                if(responseFormat == "txt") response = xhr.responseText;
                if(responseFormat == "json") response = JSON.parse(xhr.responseText);
                if (successHandler) successHandler(response);
        }
        else{
                var err_name = err_codes[xhr.status][0];
                var err_state = err_codes[xhr.status][1];
                var fullDescription = err_codes[xhr.status][2];
                if(errorHandler)
                    errorHandler(xhr.status);
                else
                    alert("Error " + xhr.status + " : " + err_name + "\n[" + err_state + " - " + fullDescription+"]");
        }
    }
    xhr.onerror = function() {
        alert("Error: No response from server.");
    }
    // Send data to server
    xhr.open('POST', req);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    //=========================================================================
    /****  include  in template  ****/
    var csrf_token = document.getElementsByName("csrfmiddlewaretoken")[0].value;
    /****  render csrf in views.py  ****/
    //var csrf_token = "{{ csrf_token }}"
    xhr.setRequestHeader("X-CSRFToken", csrf_token );
    //=========================================================================
    xhr.send(params);
}

function PostData(){
    var div2 = document.getElementById("div2");
    function success(response){
        div2.innerHTML = response;
    }
    jsonStr = JSON.stringify({"key1":"a","key2":"b"});
    params = 'name=John&json='+jsonStr;
    POST("reply/",params,success);
}

window.onload=function(){
    var button2 = document.getElementById('test2');
    button2.onclick = PostData;
}

</script>

<html>

    Server response:<div id="div2" style="height:1.5em; width:100%; border: 1px solid black;"></div>
    <p>
    <button id="test2" type="button" >Test</button>
    </p>

</html>
Server response: