I created a chatbot in which, first, I’ll receive a response. In the form, there is a last field that has a value, and I want to send that value as a user message. The bot is working fine, but when I click on ‘chatsubmit,’ it refreshes the page. e.preventDefault() is not working because it is false, but without false, I can’t send the values.
const submitForm = async (e, val) => {
if (e) { e.preventDefault(); }
if (!conversationId) {
console.error('conversationId is not set.');
return;
}
document.querySelector("#chat-submit").disabled = true;
let x = document.forms["form-feedback-data"]["message"];
let message = val || x.value;
console.log('Submitting message:', message);
// Send user message to API
await sendToApi(conversationId, "user", message);
if (message !== "") {
let aud = new Audio("https://backend.aiduals.com/assets/userMusic.mp3");
aud.play();
// Display user message in chat window
let userDiv = `
<div class="aidual_chatbot_wrap">
<div style="display: flex; align-items: center; justify-content: end;">
<div>
<span class="aidual_chatbot_date2">
<strong>${guestName.length > 0 ? guestName : "Guest"}</strong> ${generateDate()}
</span>
</div>
<div class="aidual_chatbot_wimg2">
<img src="${avtarUrl.length > 0 ? avtarUrl : "https://backend.aiduals.com/assets/user.png"}" alt="" />
</div>
</div>
<div class="aidual_chatbot_wchat2">
${message}
</div>
</div>`;
let blinkMsg = `
<div style="display: flex; padding-left: 0px;" id="typing-feed-active">
<span style="color: #555; font-size: 13px; font-weight: 500; display: flex; margin-top: 6px;">
<span style="margin-right: 5px">Do Tasks AI</span> is <span id="blinkChangeMsg" style="margin-left: 5px">typing</span>
</span>
<div class="typing">
<span></span>
<span></span>
<span></span>
</div>
</div>`;
typingInterval = setInterval(() => {
typingIndex++;
if (typingIndex === 6) {
typingIndex = 0;
}
let typingMsgData = document.getElementById("blinkChangeMsg");
typingMsgData.innerText = arrTyping[typingIndex];
}, 5000);
const chatWindow = document.getElementById("mainChatWindowBlock");
chatWindow.insertAdjacentHTML("beforeend", userDiv);
chatWindow.insertAdjacentHTML("beforeend", blinkMsg);
if (chatWindow.clientHeight < chatWindow.scrollHeight) {
chatWindow.scrollBy(0, chatWindow.scrollHeight);
}
// Call onCreateMessage to get AI response
onCreateMessage(message, typingInterval);
if (!val) {
x.value = "";
}
}
}
async function onFormSubmit(e) {
e.preventDefault();
loader.style.display = "inline-block";
// Gather form data
const data = {
name: document.forms["form-data-main"]['name'].value,
email: document.forms["form-data-main"]['email'].value,
phone: document.forms["form-data-main"]['phone'].value,
text: document.forms["form-data-main"]['message'].value,
};
// Store the guest name
guestName = data.name;
let value = data.text;
removeMsg();
document.querySelector("#form-container-box").style.display = "none";
mainWindow.style.display = "block";
chatBox.style.display = "block";
try {
// Send POST request to create a conversation
const response = await fetch("https://dotasks.in/api/create-conversation", {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(data)
});
const result = await response.json();
if (result.status) {
conversationId = result.cid;
console.log('The conversation id is:', conversationId);
// Store feedData in a cookie
feedData = { cid: conversationId };
document.cookie = `feedData=${JSON.stringify(feedData)}`;
// Fetch the conversation
// await fetchChatData(conversationId);
newFeed = feedData;
submitForm(false, value); // value is going from here
// Clear form fields
document.forms["form-data-main"]['name'].value = "";
document.forms["form-data-main"]['email'].value = "";
document.forms["form-data-main"]['phone'].value = "";
document.forms["form-data-main"]['message'].value = "";
} else {
console.error("Failed to create conversation:", result.message);
}
} catch (error) {
console.error("Error creating conversation:", error);
} finally {
loader.style.display = "none";
}
};
<div class="">
<div class="message-input">
<form class="message_input_wrap" id="form-feedback-data">
<!--<span class="chat_icon"><img-->
<!-- src="https://reeelapps-app.s3.us-west-2.amazonaws.com/aistaff/hire_staff_img/chat-icon.png"-->
<!-- alt="" /></span>-->
<input type="text" class="chat_typing_box"
placeholder="Write your message..." name="message" required />
<!--<div class="voice-icon-wrapper">-->
<!-- <i id="start-btn" class="chat-send fa-solid fa-microphone"-->
<!-- onclick="startRecognition()">-->
<!-- </i>-->
<!-- <i id="stop-btn" style="display:none;"-->
<!-- class="chat-send fa-solid fa-pause" onclick="startRecognition()">-->
<!-- </i>-->
<!--</div>-->
<button class="chat-send" type="submit" id="chat-submit"><img
src="https://reeelapps-app.s3.us-west-2.amazonaws.com/Reputor_ai/send.png"
alt="" /></button>
</form>
</div>
I want to submit the form first, then receive the value as user input, and the page should not refresh when I send the message.