Skip to content
AndoryuGuo edited this page Apr 8, 2019 · 11 revisions

Usage of Ajax

Ajax is used almost everywhere in our project. The identity of current user (the user who initiated the request) will be identified by a header x-request-user-id: request_user_id. request_user_id will be declared as long as the page is loaded, by request.user.id.

In order to determine which host we should send request, we append a parameter host to the url that has possibility the content are from remote server. For example, when viewing home page, current user is intending to check another author's profile. Then the url he/she is directing to is http://our-host.com/author/user-be-viewed-id/info/?host=host-user-be-viewed-located. Therefore, when back end receive this url, the host that content comes from is identified. And this information will be given to front-end when rendering the profile page. Then, the front end can send required requests to the host given by back end, which is the host where content should be got.

Here is an example:

When I am on my home page: http://conet-socialdistribution.herokuapp.com/author/7afa94d2-0e2f-41b4-947e-7fa46a91375b/.

I decide to see another user's profile, and the profile link is: http://conet-socialdistribution.herokuapp.com/author/902f61fd-9513-49cf-9722-17d40230976d/info/?host=https://myblog-cool.herokuapp.com/.

The back end get the author's id 902f61fd-9513-49cf-9722-17d40230976d, the host this user is located https://myblog-cool.herokuapp.com/. Then the back end will looks for the Node object with host https://myblog-cool.herokuapp.com/, and get the username and password of that node object.

Then, back end will send current_user_id, user_be_viewed_id, and remote information to the front end when rendering.

In the end, front end receives everything back end passed. And send required requests to https://myblog-cool.herokuapp.com/ to get information we need.

In front end, the following APIs are sent via XMLHTTPRequest:

The following APIs are sent via fetch:

XMLHttpRequest() POST function:

Since we only send POST request to our own server when we are using XMLHttpRequest(), we have only header x-csrftoken to authenticate current user.

// function to send JSON Http post request
function sendJSONHTTPPost(url, objects, callback, remote={}) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            try {
                callback(xhr.response);
            }
            catch (e) {
                console.log('XHR Error: ' + e.name);
            }
        }
    };
    if (xhr.overrideMimeType) {
        xhr.overrideMimeType("application/json");
    }
    xhr.open("POST", url);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Accept", "application/json");
    xhr.setRequestHeader("x-csrftoken", csrf_token);    // csrf_token is global. Initiated as long as each page is loaded.
    xhr.send(JSON.stringify(objects));
}

XMLHttpRequest() GET Function

function sendJSONHTTPGet(url, objects, callback, remote={}) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                callback(xhr.response);
            }

        }
    };
    if (xhr.overrideMimeType) {
        xhr.overrideMimeType("application/json");
    }
    xhr.open("GET", url);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Accept", "application/json");
    
    // if remote is an empty onject. We know it's a local server reqeust. Use x-csrf-token
    // Else, it's a remote request. Use Authorization
    if (Object.keys(remote).length === 0 && remote.constructor === Object) {
        xhr.setRequestHeader("x-csrftoken", csrf_token);
    } else {
        xhr.setRequestHeader("Authorization", "Basic " + btoa(remote.username + ":" + remote.password));
    }
    
    // try to set x-request-user-id header.
    try{
        xhr.setRequestHeader("x-request-user-id", request_user_id);
    }catch{
        console.log("no");
    }
    xhr.send(JSON.stringify(objects));
}

Fetch POST function:

This is an example of accepting a friendrequest via fetch

fetch(url, {
        method: "POST",
        mode: "cors",
        credentials: "same-origin",
        headers: {
            "x-csrftoken": csrf_token,
            "Content-Type": "application/json"
        },
        body: JSON.stringify(sendObjcet),
}).then(res=>{
        if (res.status == 200)
            fetchGetRequest('/notification')
            .then(res=>window.location.reload(true));
        else
            return res.json();
}).then(data=>alert(data['message']));

Fetch GET function:

This is an example how does the normal GET request is sent via fetch

fetch(url, {
        method: "GET",
        mode: "cors",
        credentials: "same-origin",
        headers: {
            "Accept": "application/json"
        }
});

Fetch DELETE function:

This is an example of a post being deleted via fetch

fetch(url, {
    method: "DELETE",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    headers: {
        "x-csrftoken": csrf_token
    },
    redirect: "follow",
    referrer: "no-referrer",
})
.then(response => {
  if (response.status === 204)  {
    window.location.reload(true);
  }
  else
  {
    alert(response.status);
  }
});

Fetch PUT function

This is an example of editing user profile via fetch

fetch(url, {
        method: "PUT",
        mode: "cors",
        credentials: "same-origin",
        headers: {
            "Content-Type": "application/json",
            "x-csrftoken": csrf_token,
        },
        body: JSON.stringify(profileInfo),
    }).then(res => {
        if(res.status == 400)
            console.log("input data is invalid");
        else
            window.location.reload(true);
});

Ajax in each page

The following APIs are used:


APIs used in this page are mainly based on user being viewed (the author current user is watching).

The following APIs are used:

The following API is used only when user are viewing his/her own profile page:

The following API is used only when user are viewing other user's profile page:

  • POST /friendrequest
    • To send friend request to the user being viewed.
    • We send this POST request to our own server, in order to check if the user_being_viewed is stored in our local database or not. If not, another POST request will sent through back-end to the server user_being_viewed is located.

The following APIs are used only when viewing profile of authors who are on local server:


The following API is used on this page:


The following API is used on this page:


The following API is used on this page:


The following API is used on this page: