Skip to content

AJAX Front End

Leah Copeland edited this page Apr 1, 2021 · 20 revisions

Getting Non-Followers

/service/author/{AUTHOR_ID}/nonfollowers/ to retrieve a json response containing users that the logged in user may follow/send a friend request to

  • Request method: GET

function fetchJSON(url) {
            var request = new Request(url);
            return fetch(request).then((response) => {
                if (response.status === 200 || response.status == 404) { 
                    return response.json(); // return a Promise
                } else {
                    alert("Something went wrong: " + response.status);
                }
            });
        }

Getting Followers

/service/author/{AUTHOR_ID}/followers/ to retrieve a json response containing users that are following the logged in user (sending a friend request to the logged in user)

  • Request method: GET

function fetchJSON(url) {
            var request = new Request(url);
            return fetch(request).then((response) => {
                if (response.status === 200 || response.status == 404) { 
                    return response.json(); // return a Promise
                } else {
                    alert("Something went wrong: " + response.status);
                }
            });
        }

Getting Friends

/service/author/{AUTHOR_ID}/friends/ to retrieve a json response containing users that are friends with the logged in user (both users are following each other)

  • Request method: GET

function fetchJSON(url) {
            var request = new Request(url);
            return fetch(request).then((response) => {
                if (response.status === 200 || response.status == 404) { 
                    return response.json(); // return a Promise
                } else {
                    alert("Something went wrong: " + response.status);
                }
            });
        }

Getting Friends

/service/author/{AUTHOR_ID}/friends/ to retrieve a list of users that are following the logged in user (that are friend requesting them)

  • Request method: GET

function fetchJSON(url) {
            var request = new Request(url);
            return fetch(request).then((response) => {
                if (response.status === 200 || response.status == 404) { 
                    return response.json(); // return a Promise
                } else {
                    alert("Something went wrong: " + response.status);
                }
            });
        }

Following user

/service/author/{AUTHOR_ID}/followers/{FOREIGN_AUTHOR_ID}/ to follow a LOCAL user/friend request a LOCAL user

  • Request method: PUT -!important: in this instance {AUTHOR_ID} is the author the logged in user is following and {FOREIGN_AUTHOR_ID} is the current logged in users id
follow(url).done(function(response) {
                console.log(response);
            });

function follow(url){
            return $.ajax({
                url: url,
                type: 'PUT',
                contentType: "application/json",
                success: function(result) {
                    console.log(result)
                   
                }
            })
        }

Following a user back

/service/author/{AUTHOR_ID}/followers/{FOREIGN_AUTHOR_ID}/ to follow back a LOCAL user/friend request a LOCAL user back

  • Request method: PUT
  • !important: in this instance {AUTHOR_ID} is the user being followed/friend requested and {FOREIGN_AUTHOR_ID} is the user who is sending the follow/friend request
AddFollowerBack(url).done(function(response) {
                console.log(response);
            });

function AddFollowerBack(url){
            return $.ajax({
                url: url,
                type: 'PUT',
                contentType: "application/json",
                success: function(result) {
                    console.log(result)
                }})
        }

**Deleting a friend <:-( **

/service/author/{AUTHOR_ID}/followers/{FOREIGN_AUTHOR_ID}/ to remove a LOCAL friend from a friend list (also removes friends from followers)

/service/author/{FOREIGN_AUTHOR_ID}/followers/{AUTHOR_ID}/ to remove a LOCAL friend from a friend list (also removes friends from followers)

  • Request method: PUT
  • !important: in this instance {AUTHOR_ID} is the author the logged in user is following and {FOREIGN_AUTHOR_ID} is the current logged in users id
  • !important: calls must be made to both url listed above

function remove(url){
            $.ajax({
                url: url,
                type: 'DELETE',
                contentType: "application/json",
                success: function(result) {
                    console.log(result)
                }
            })
        }

Getting All Friends a User Has

/service/author/{AUTHOR_ID}/friends/ to retrieve a list of users the author who is logged in may follow (requires authorization)

  • Request method: GET
function getFriends() {
    var uuid = "{{uuid}}";
    var pre_url = "/service/author/"
    var url = pre_url + uuid + "/friends/" 
    fetchJSON(url).then((json) => { //another callback
        try{
     
            for (var i = 0; i < json.items.length; i++) { 
                 var user_id;
                 console.log(json)
                 if ("host" in json.items[i]){
                      if (json.items[i].host == citrus_network_swag_host || json.items[i].host == local_host){
                          follower_info_dict[json.items[i].id] = json.items[i].host
                          user_id = json.items[i].id
                      }else if (json.items[i].host == team_18_host){
                          follower_info_dict[json.items[i].authorID] = json.items[i].host
                          user_id = json.items[i].authorID
                      }else if (json.items[i].host == team_3_host){
                          follower_info_dict[json.items[i].id] = json.items[i].host
                          user_id = json.items[i].id
                      }else{
                          console.log("host was neither team18, team3  or citrus")
                      }
                  }else{
                         console.log("Host was not provided")
                  }

                $("#friends-select")
                .append('<option value="'+ json.items[i].id +'">' + json.items[i].displayName + '</option>');
                } 
            }catch(err){
                // console.log(uuid)
                $("#friends-select") 
                .append('<option value="public">Public</option>');
            }
        });
}

Update an existing post

/service/author/{AUTHOR_ID}/posts/{POST_ID} will update the existing post that the author made.(requires authorization)

  • Request method: PUT
function updatePost() {
    var uuid = "{{ uuid }}";
    var pre_url = "/service/author/";
    var url = pre_url + uuid + "/posts/";
    url += "{{ post_id }}/";
    var title = document.getElementById("title-name").value;
    var content = document.getElementById("post-textarea").value;
    if (title === ""){
        alert("Don't submit an empty post");
        return false;
    }
    var visibility = document.getElementById("post-visibility").value;
    var markdown;
    if(document.getElementById('btnradio1').checked){
        markdown = document.getElementById('btnradio1').value;
    }
    if(document.getElementById('btnradio2').checked){
        markdown = document.getElementById('btnradio2').value;
    }
    markdown = "false";
    var shared = document.getElementById("friends-select").value;
    var categories_field = $("#categories");
    var categories;
    if (categories_field.is(":hidden")){
        categories = "";
    } else {
        categories = document.getElementById('categories').value;
    }

    var mJson = {
            title: title,
            description: "mock desc",
            categories: categories,
            content: content,
            origin: window.location.origin,
            visibility: visibility,
            shared_with: shared,
    };
    $.ajax({
        type: 'PUT',
        url: url,
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(mJson),
        success: function(result) {
            location.reload();
        }
    });
}

Delete existing post

/service/author/{AUTHOR_ID}/posts/{POST_ID} will delete the existing post that the author made.(requires authorization)

  • Request method: DELETE
function deletePost() {
    var uuid = "{{ uuid }}";
    var pre_url = "/service/author/";
    var url = pre_url + uuid + "/posts/";
    url += "{{ post_id }}/";
    $.ajax({
        type: 'DELETE',
        url: url,
        contentType: "application/json",
        success: function(result) {
            window.location.href = "{% url 'home_url'%}"
        }
    });
}

Getting the Inbox

/service/author/{AUTHOR_ID}/inbox/ will retrieve the author's inbox.(requires authorization)

  • Request method: GET

function getInbox() {
    var uuid = "{{uuid}}";
    url = window.location.origin;
    url += "/service/author/" + uuid +"/inbox/";
    fetchJSON(url).then((json) => {
        //console.log(json.posts);
        for(var i of json.items){
            if (i.type.toLowerCase().includes("post") || i.type.toLowerCase().includes("like") || 
                    i.type.toLowerCase().includes("follow")) {
                var newElement = document.createElement('div');
                var classAttr = document.createAttribute("class");
                classAttr.value = "row justify-content-center mt-1 mb-1 ";
                newElement.setAttributeNode(classAttr);
                if (i.type == "post") {
                    var postHtml = '<div class="col-md-6 col-sm-10 position-relative">' + 
                        '<a class="card card-link" href=../service/author/' + 
                        i.author.id + '/view-post/' + i.id + '/>' + 
                        '<div class="card-header"><p><b>' + 
                        i.author.displayName + '</b></p></div>' 
                        postHtml += '<div class="card-body"><p>Shared a post with you!' + 
                            '</p></div></a></div>'
                    
                    newElement.innerHTML = postHtml;
                } else if (i.type == "follow") {
                    var postHtml = '<div class="col-md-6 col-sm-10 position-relative">' + 
                        '<a class="card card-link" href=../followers/>' + 
                        '<div class="card-header"><p><b>' + 
                        i.actor.displayName + '</b></p></div>' 
                        postHtml += '<div class="card-body"><p>Is following you!' + 
                            '</p></div></a></div>'
                    
                    newElement.innerHTML = postHtml;
                } else {
                    var postHtml = '<div class="col-md-6 col-sm-10 position-relative">' + 
                        '<div class="card">' + 
                        '<div class="card-header"><p><b>' + 
                        i.author.displayName + '</b></p></div>' 
                        postHtml += '<div class="card-body"><p>' + i.summary +  
                            '</p></div></div></div>'
                    
                    newElement.innerHTML = postHtml;
                }

                document.querySelector(".stream-inbox").appendChild(newElement);
            }
        }
    });
}

Delete the Inbox

/service/author/{AUTHOR_ID}/inbox/ will delete the author's inbox.(requires authorization)

  • Request method: DELETE
function fetchDelete(url) {
    return fetch(url, {method: "DELETE"}).then((response) => {
        if (response.status === 200 || response.status === 404) { // OK
            return response.json(); // return a Promise
        } else {
            alert("Something went wrong: " + response.status);
        }});
    }

Get a stream, used in viewProfile.html and stream.html

/home-test/ will get the author's stream.(requires authorization)

  • Request method: GET
function getStream() {
    var uuid = "{{uuid}}";
    fetchJSON("{% url 'get_stream' %}").then((json) => {
        //console.log(json.posts);
        console.log(json)
        for(var i in json.posts){
            var newElement = document.createElement('div');
            var classAttr = document.createAttribute("class");
            classAttr.value = "col-md-10 col-sm-12 mt-1 mb-1 position-relative";
            if (json.posts[i].author.id.includes("/author/")) {
                json.posts[i].author.id = json.posts[i].author.id.split("/author/")[1]
            }
            if (json.posts[i].id.includes("/posts/")) {
                json.posts[i].id = json.posts[i].id.split("/posts/")[1]
            }
            newElement.setAttributeNode(classAttr);
            let url = "{% url 'render_profile' %}" + json.posts[i].author.id
            var postHtml = '<div class="card">' + '<div class="card-header"><a class="card-link" href="' + url + '">' + 
                '<p style="margin: 0;"><strong>' + json.posts[i].author.displayName + '</strong></p>' +
                '<p style="margin: 0;">' + json.posts[i].published + ' | ' + json.posts[i].origin + '</p>' +
                '</a>';

            for (var j in json.posts[i].categories) {
                postHtml += '<a class="btn mt-1 btn-sm btn-outline-info rounded-pill" href="#tag">' + json.posts[i].categories[j] + '</a>'
            }
            postHtml += '</div><a class="card-body card-link" href=../service/author/' + 
                json.posts[i].author.id + '/view-post/' + json.posts[i].id + '/>' + 
                '<h6 class="font-weight-bold">' + json.posts[i].title + '</h6>';
            
            if (json.posts[i].contentType === "image/png;base64" || json.posts[i].contentType === "image/jpeg;base64"){
                postHtml += '<img src=\"' + json.posts[i].content + '\"/>';
            } else if (json.posts[i].contentType === "text/markdown") {
                postHtml += marked(json.posts[i].content)
            } else{
                let lines = json.posts[i].content.split('\n');
                
                postHtml += '<p>';
                for (var j of lines) {
                    postHtml += j + '<br>'
                }
                postHtml +='</p>';
                // console.log(marked(json.posts[i].content));
            }
            newElement.innerHTML = postHtml;

            document.querySelector(".stream-post").appendChild(newElement);
        }
    });
}

Get the author's github activity

/service/author/<author_id>/github/ will get the author's github.

  • Request method: GET
function getGithubActivity() {
    var uuid = "{{uuid}}";
    var url = "/service/author/" + uuid + "/github" // :service/author/{AUTHOR_ID}
    fetchJSON(url).then((json) => { // another callback
        document.querySelector('#githubActivity').style.display = "flex";
        try{
            document.querySelector("#gitHubName").innerText = new String ("GitHub Activity for "+json.events[0].name)
            document.querySelector("#github-header").style.background = "#e6d0a0";
            document.querySelector("#gitHubName").href = new String("https://github.com/"+json.events[0].name)
            for (var i in json.events) {
                var event = formatEvent(json.events[i]);
                $('#githubBody').append(event + "<br/><br/>");
            }
        }catch(err){
            document.querySelector("#github-header").style.background = "#62afdd";
            document.querySelector("#githubBody").innerText = "Cannot get GitHub activity";
            document.querySelector("#profileref").style.display = "flex";
        }
    });
}

Get all the public posts

/public-posts/ will get the author's github.

  • Request method: GET
function getStream() {
    fetchJSON("{% url 'public_posts' %}").then((json) => {
        for(var i in json.message){
            if (json.message[i].author.id.includes("/author/")) {
                json.message[i].author.id = json.message[i].author.id.split("/author/")[1]
            }
            if (json.message[i].id.includes("/posts/")) {
                json.message[i].id = json.message[i].id.split("/posts/")[1]
            }
            var newElement = document.createElement('div');
            var classAttr = document.createAttribute("class");
            classAttr.value = "col-md-10 col-sm-12 mt-1 mb-1 position-relative";
            newElement.setAttributeNode(classAttr);
            let url = "{% url 'render_profile' %}" + json.message[i].author.id
            var postHtml = '<div class="card">' + '<div class="card-header"><a class="card-link" href="' + url + '">' + 
                '<p style="margin: 0;"><strong>' + json.message[i].author.displayName + '</strong></p>' +
                '<p style="margin: 0;">' + json.message[i].published + ' | ' + json.message[i].origin + '</p>' +
                '</a>';

            for (var j in json.message[i].categories) {
                postHtml += '<a class="btn mt-1 btn-sm btn-outline-info rounded-pill" href="#tag">' + json.message[i].categories[j] + '</a>'
            }
            postHtml += '</div><a class="card-body card-link" href=../service/author/' + 
                json.message[i].author.id + '/view-post/' + json.message[i].id + '/>' + 
                '<h6 class="font-weight-bold">' + json.message[i].title + '</h6>';
            
            if (json.message[i].contentType === "image/png;base64" || json.message[i].contentType === "image/jpeg;base64"){
                postHtml += '<img src=\"' + json.message[i].content + '\"/>';
            } else if (json.message[i].contentType === "text/markdown") {
                postHtml += marked(json.message[i].content)
            } else{
                let lines = json.message[i].content.split('\n');
                
                postHtml += '<p>';
                for (var j of lines) {
                    postHtml += j + '<br>'
                }
                postHtml +='</p>';
                // console.log(marked(json.message[i].content));
            }
            newElement.innerHTML = postHtml;

            document.querySelector(".stream-post").appendChild(newElement);
        }
    });
}

Post a comment to a specific post

/service/author/{AUTHOR_ID}/view-post/{POST_ID}/comment/ will create a comment

  • Request method: POST
$.ajax({
    url: "/service/author/{{author_id}}/view-post/{{post_id}}/comment/",
    type: "POST",
    dataType: 'json',
    contentType: "application/json",
    data: JSON.stringify(comment),
    success: function(data) {
        ...
    }
});

Get the comments of a specific post

/service/author/{AUTHOR_ID}/view-post/{POST_ID}/comment/ will get the comments of the post

  • Request method: GET
$.ajax({
    url: "/service/author/{{author_id}}/view-post/{{post_id}}/comment/",
    type: "GET",
    dataType: 'json',
    success: function(data) {
        var commentHtml = ""
        for (var i in data.comments) {
            let url = "{% url 'render_profile' %}" + data.comments[i].author.id
            commentHtml += '<div class="card mt-1 mb-1"><div class="card-header"><a class="card-link" href="' + url + '">' + 
            '<p style="margin: 0;"><strong>' + data.comments[i].author.displayName + '</strong> | ' + data.comments[i].published + 
            '</p></a></div><div class="card-body"><p>' + data.comments[i].comment + '</p>' + 

            // Like buttons not yet implemented due to no like API
            // '<button type="button" class="ml-3 btn btn-light btn-sm rounded-pill">' + 
            // '<em class="bi-hand-thumbs-up-fill" style="color: cornflowerblue;"></em></button>' + 
            // '<button type="button" class="ml-3 btn btn-light btn-sm rounded-pill">' + 
            // '<em class="bi-hand-thumbs-up-fill"></em></button>' + 
            '</div></div>';
        }
        $('.comments').html(commentHtml);
    }
});

Get a post

/service/author/{AUTHOR_ID}/get-posts/{POST_ID}/ will get the comments of the post

  • Request method: GET
$.ajax({
    url: "/service/author/{{author_id}}/get-posts/{{post_id}}/",
    type: "GET",
    dataType: 'json',
    success: function(post) {
        console.log(post);
        $('.author-name').html(post.author.displayName)
        $('.published').html(post.published)
        var tagHtml = ''; 
        for (var i in post.categories) {
            tagHtml +=  '<a class="btn mt-1 btn-sm btn-outline-info rounded-pill" href="#tag">' + 
            post.categories[i] + '</a>';
        }
        $('.post-tag').html(tagHtml);
        $('.post-title').html(post.title);
        if (post.contentType === 'text/markdown'){
            $('.post-content').html(marked(post.content));
        } else if (post.contentType === "image/png;base64" || post.contentType === "image/jpeg;base64"){
            $('.post-content').html('<img src=\"' + post.content + '\"/>');
        } else {
            let lines = post.content.split("\n")
            for (var i of lines) {
                $('.post-content').append(i + '<br>');
            }
        }
        for (var i in post.comments) {
            let url = "{% url 'render_profile' %}" + post.comments[i].author.id
            var commentHtml = '<div class="card mt-1 mb-1"><div class="card-header"><a class="card-link" href="' + url + '">' + 
                '<p style="margin: 0;"><strong>' + post.comments[i].author.displayName + '</strong> | ' + post.comments[i].published + 
                '</p></a></div><div class="card-body"><p>' + post.comments[i].comment + '</p>' + 

                // Like buttons not yet implemented due to no like API
                // '<button type="button" class="ml-3 btn btn-light btn-sm rounded-pill">' + 
                // '<em class="bi-hand-thumbs-up-fill" style="color: cornflowerblue;"></em></button>' + 
                // '<button type="button" class="ml-3 btn btn-light btn-sm rounded-pill">' + 
                // '<em class="bi-hand-thumbs-up-fill"></em></button>' + 
                '</div></div>';
            $('.comments').append(commentHtml);
        }
    },
    error: function() {
        window.location.replace('/home')
    }
});

Clone this wiki locally