· 6 years ago · Feb 03, 2020, 10:26 PM
1function add_message(event) {
2 // Takes form data and asynchronously adds a comment to the blog post using Fetch API and Flask
3
4 event.preventDefault();
5
6 let name = document.getElementById('form_name');
7 let comment = document.getElementById('form_comment');
8
9 // Gets blog foreign key needed on backend -- example.com/blog/3/
10 let pathArray = window.location.pathname.split('/');
11 let post_id = pathArray[2];
12
13
14 let msgObj = {
15 name: name.value,
16 comment: comment.value,
17 post_id: post_id
18 };
19
20 if (comment.value.length > 200) {
21
22 flashErrorMessage('Sorry! Your comment exceeded the max character limit of 200.');
23 return console.log('Exited from function!');
24
25 }
26
27 // Send a POST request to flask backend with form data.
28 fetch(`${window.origin}/add_comment/`, {
29 method: 'POST',
30 credentials: 'include',
31 body: JSON.stringify(msgObj),
32 cache: 'no-cache',
33 headers: {
34 'Content-Type': 'application/json'
35 }
36 })
37 .then(function (response) {
38
39 if (response.status !== 200) {
40
41 flashErrorMessage('Oops! Something went wrong. Please try again later.');
42 return console.log('Exited from function!');
43
44 }
45
46 response.json().then(function(data) {
47
48 createCommentDiv(data);
49
50 })
51 });
52 }
53
54
55 function flashErrorMessage(message) {
56
57 let div = document.createElement('div');
58 div.className = "alert alert-danger col-xl-6 offset-xl-3 col-lg-8 offset-lg-2 col-md-8 offset-md-2 text-center";
59 div.innerHTML = `${message}`;
60
61 let flash_here = document.getElementById('flash_here');
62 flash_here.before(div);
63 flash_here.reset();
64 };
65
66
67 function createCommentDiv(data) {
68
69 let comment_section = document.getElementById('comment_section');
70 let flash_here = document.getElementById('flash_here');
71
72 let li = document.createElement('li');
73 li.className = "list-group-item";
74
75 li.innerHTML = `<strong>${data.message.name}</strong> said on ${data.message.created_at}: <br> ${data.message.message}`;
76
77 let div = document.createElement('div');
78 div.className = "alert alert-success col-xl-6 offset-xl-3 col-lg-8 offset-lg-2 col-md-8 offset-md-2 text-center";
79 div.innerHTML = 'Great! Your comment has been posted.';
80
81 comment_section.prepend(li);
82 flash_here.before(div);
83 flash_here.reset();
84
85 };