I'm trying to create a chatroom application using Flask and update the chat via AJAX calls. I'm storing all of my chat messages in a JSON file in the root directory ('root/chat_data.json') that looks like this:
{
"id": 0,
"room": "user1room",
"owner": "user1",
"messages":
[
{
"sender": "admin",
"text": "this should pop up first in user1room!",
"date": "[2024-01-01 12:00:01]"
},
{
"sender": "admin",
"text": "this should pop up second in user1room!",
"date": "[2024-01-01 12:30:01]"
}
]
}
I'm able to retrieve and display the list of pre-existing chats for a given chatroom in Flask just fine, but I'm having trouble actually posting messages by writing to the .JSON file. My current implementation in root/templates/chat.html uses this form
<form action="javascript:sendMessage()" method="post">
<dl>
<dt>Message
<dd><input type="text" id="msgContent" name="newMessage">
<dd><input type="submit" id="sendMsg" value="Send Message">
</dl>
</form>
To call this function in a script tag that will eventually append the input to the JSON file
<script>
async function sendMessage()
{
const response = await fetch('../chat_data.json', {
dataType: 'json',
headers: {
'Accept': 'Application/json',
"Content-Type" : "Application/json",
}}).then(response => response.json())
.then(function(chat_data) {
console.log(chat_data);
});
};
</script>
As you can see, I'm just trying to receive and print out the chat data as of right now, but I keep getting a 404 error when I try fetching '../chat_data.json'. I've also tried './chat_data.json', '/chat_data.json', and any other permutations of relative file path access. Where is chat_data.json stored when I run my application and how can I properly access it?
Additionally, I'm also getting another error that states "
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON".
I know this means that fetch is returning HTML, but how can I get it to properly return JSON once I'm able to access chat_data.json?
As I said, chat_data.json is in the root directory and the html file (chat.html) is at templates/chat.html. Thanks!