GET vs. POST

Aug. 7, 2020

  • frontend.png Front-End
  • server1.jpg Back-End

Survey of GET and POST in different media: html, javascript (xmlhtprequest), jquery (ajax), python requests

Basic distinctions from GET and POST request are below: For a data fields like that: firstname=Jane lastname=#Me a GET request will convert non-alphanumeric characters by '%HH' a percent sign and two hexadecimal digits representing the ASCII code of the character: /echo?firstname=Jane&lastname=%23Me while a POST request will send parameters unmodified, appendig them in a body data (including eventually files for uploading) boundary separated, so being more efficient for large amount of data.

POST request of type "application/x-www-form-urlencoded" will not handle files while a "multipart/form-data" type will do. A html form of enctype "application/x-www-form-urlencoded" will submit to server only the file name, not the file itself.

Example raw request will be like that:

GET /echo?firstname=Jane&lastname=%23Me HTTP/1.1
Host: 192.168.0.102:8000
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.0.102:8000/
Cookie: csrftoken=pKI9T39YjteYJAtpzLxVQ4ZeTIVBKP4s
Connection: keep-alive
Upgrade-Insecure-Requests: 1

POST /echo HTTP/1.1
Content-Length: 433
Accept-Language: en-US,en;q=0.5
Accept-Encoding:  gzip, deflate
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent:  Mozilla/5.0 (Windows NT 6.3; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Host: 192.168.0.102:8000
Referer: http://192.168.0.102:8000/
Cookie: csrftoken=pKI9T39YjteYJAtpzLxVQ4ZeTIVBKP4s
Upgrade-Insecure-Requests: 1
Content-Type:  multipart/form-data; boundary=---------------------------17021676630187
-----------------------------17021676630187
Content-Disposition: form-data; name="firstname"
Jane
-----------------------------17021676630187
Content-Disposition: form-data; name="lastname"
#Me
-----------------------------17021676630187
Content-Disposition: form-data; name="file"; filename="1.txt"
Content-Type: text/plain
This is a text file with
two lines of text.
-----------------------------17021676630187--

As a test example we will use the forms below. For simplicity we will use txt files and amounts of bytes uploaded will be limited to 200 bytes.

GET and POST in HTML

Form 1 - GET
<!-- default method is GET -->
<form action="echo">
  First name:<br>
  <input type="text" name="firstname"><br>
  Last name:<br>
  <input type="text" name="lastname"><br>
  <input type="submit" value="Submit">
</form>

Form 2 - POST : enctype="application/x-www-form-urlencoded"
<form action="echo" method="post" enctype="application/x-www-form-urlencoded">
  {% csrf_token %}
  First name:<br>
  <input type="text" name="firstname"><br>
  Last name:<br>
  <input type="text" name="lastname"><br>
  <input type="file" name="file"><br>
  <input type="submit" value="Submit">
</form>

Form 3 - POST : enctype="multipart/form-data"
<form action="echo" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  First name:<br>
  <input type="text" name="firstname"><br>
  Last name:<br>
  <input type="text" name="lastname"><br>
  <input type="file" name="file"><br>
  <input type="file" name="file0"><br>
  <input type="submit" value="Submit">
</form>
Form 1 - GET
First name:

Last name:


Form 2 - POST : enctype="application/x-www-form-urlencoded" (Sending only file names not the files itself.)
First name:

Last name:



Form 3 - POST : enctype="multipart/form-data"
First name:

Last name:




The same requests are reproduced below, in different contexts:

GET and POST in Javascript (XmlHttpRequest)

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

function message(msg){
    alert(msg);
}

xhr1 = getXHR();
if(!xhr1) message("Ajax is not supported by your browser!");

xhr1.onload = function() {
    if (xhr1.status === 200){
        message(xhr1.responseText);
    }
    else{
        message("Error " + xhr1.status);
    }
}

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

function send1(){
    var form1 = document.getElementById("form1");
    var url = form1.action;
    firstname = encodeURIComponent(form1.firstname.value);
    lastname = encodeURIComponent(form1.lastname.value);
    var params = "?firstname=" + firstname + "&lastname=" + lastname + "&medium=js";
    xhr1.open('GET', url+params);
    xhr1.send(null);
}
Form1

...

function send2(){
    var form2 = document.getElementById("form2");
    var url = form2.action;
    firstname = form2.firstname.value;
    lastname = form2.lastname.value;
    var params = "firstname=" + firstname + "&lastname=" + lastname + "&medium=js";
    xhr2.open('POST', url);
    xhr2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    //Django settings==========================================================
    /****  include {% csrf_token %} in template or ... ****/
    var csrf_token = document.getElementsByName("csrfmiddlewaretoken")[0].value;
    /****  ... render csrf in views.py  ****/
    //var csrf_token = "{{ csrf_token }}"
    xhr.setRequestHeader("X-CSRFToken", csrf_token );
    //=========================================================================

    xhr2.send(params);
}
Form2

...

// encoding data in a FormData structure is equivalent to a form data with content type (enctype) "multipart/form-data"

function send3(){
    var form3 = document.getElementById("form3");
    var url = form3.action;
    firstname = form3.firstname.value;
    lastname = form3.lastname.value;
    file = form3.file.files[0];
    file0 = form3.file0.files[0];

    var fd = new FormData();

    fd.append("medium","js");      
    fd.append("firstname",firstname);
    fd.append("lastname",lastname);
    if(file!=undefined) fd.append("file", file);
    if(file0!=undefined) fd.append("file0", file0);

    xhr3.open('POST', url);

    //Django settings==========================================================
    /****  include {% csrf_token %} in template or ... ****/
    var csrf_token = document.getElementsByName("csrfmiddlewaretoken")[0].value;
    /****  ... render csrf in views.py  ****/
    //var csrf_token = "{{ csrf_token }}"
    xhr.setRequestHeader("X-CSRFToken", csrf_token );
    //=========================================================================

    xhr3.send(fd);
}
Form3

GET and POST in jquery

$("#button1").click(
    function(){
        var form1       = document.getElementById("form1");
        var url         = form1.action;
        firstname       = encodeURIComponent(form1.firstname.value);
        lastname        = encodeURIComponent(form1.lastname.value);
        medium          = encodeURIComponent("js");
        var req         = url + "?firstname=" + firstname + "&" + "lastname=" + lastname + "&" + "medium=" + medium;
        $.ajax({
            url: encodeURI(req),
            type: 'GET',
            success: function (data) {
                alert(data);
            },
            error: function (jqXHR , textStatus, errorThrown) {
                var msg = "Post error ";
                if (jqXHR.status !=0) msg = msg + jqXHR.status + " " + textStatus + " " + errorThrown;
                alert(msg);
            },
        });
    }
);
Form1

$("#button2").click(
    function(){
        var form2       = document.getElementById("form2");
        var url         = form2.action;
        firstname       = form2.firstname.value;
        lastname        = form2.lastname.value;
        var csrf_token = document.getElementsByName("csrfmiddlewaretoken")[0].value;

        $.ajax({
            url: encodeURI(url),
            type: 'POST',
            //setting header for Django that way or ...
            //beforeSend: function (xhr) {
            //    xhr.setRequestHeader("X-CSRFToken", csrf_token);
            //},
            headers: {
                'X-CSRFToken' : csrf_token
            },
            data: {
                firstname: firstname,
                lastname: lastname,
                medium: "js"
            },
            contentType: 'application/x-www-form-urlencoded',
            success: function (data) {
                alert(data);
            },
            error: function (jqXHR , textStatus, errorThrown) {
                var msg = "Post error ";
                if (jqXHR.status !=0) msg = msg + jqXHR.status + " " + textStatus + " " + errorThrown;
                alert(msg);
            },
        });
    }
);
Form2

$("#button3").click(
    function(){
        var form3 = document.getElementById("form3");
        var formData = new FormData(form3);  /*csrf token is included in form*/
        var formAction  = form3.action;
        formData.append("medium","js");
        file = formData.get("file");
        file0 = formData.get("file0");

        if((file !=undefined) && (file.size > 1000)) {
            alert("File " + file.name + " is more than 1000 bytes." );
            return;
        }
        if((file0 !=undefined) && (file0.size > 1000)) {
            alert("File " + file0.name + " is more than 1000 bytes." );
            return;
        }

        $.ajax({
            url : formAction,
            type : 'POST',
            data : formData,
            processData: false,  // tell jQuery not to process the data
            contentType: false   // tell jQuery not to set contentType
        }).done(
            function(data){
                alert(data);
            }
        ).fail(
            function (jqXHR , textStatus, errorThrown) {
                var msg = "Post error ";
                if (jqXHR.status !=0) msg = msg + jqXHR.status + " " + textStatus + " " + errorThrown;
                alert(msg);
        }
        );
    }
);
Form3

Return to home