Answer the question
In order to leave comments, you need to log in
How to submit an ajax form without reloading the page?
Good day! I am a beginner front. I’m working with Ajax for the first time, I ask for help in clarifying, Google didn’t help out (
I have the following task.
When you click on the button, a popup pops up, in which there is a chat window with one input. The user builds a dialogue with the bot and with each submit of the form, the data should be sent by Ajax to server, and the message from the input is moved to the chat window.
I wrote everything locally, without a server, it works, messages are received in the chat. But as uploaded to the server, when submitting, it goes to 404, or does not submit at all if you use event.preventDefault();
I tried to remove the c type="submit button and put a simple span instead, the page still reloads after submitting the form data.
Please tell me how to make the code work like on a local machine.
function code for sending data to the server:
$( document ).ready(function() {
function AjaxFormRequest() {
var messages = [].slice.call(document.getElementById('chatbot-message').querySelectorAll('.from-user'));
var lastMsg = document.getElementById('chatbot-input').value;
var filteredMessages = messages.map(
(msgBlock) => {
return msgBlock.textContent.replace('Вы: ', '')
})
console.log(filteredMessages);
console.log(lastMsg);
$.ajax({
url: "test.php",
type: "POST",
dataType: "html",
data: JSON.stringify(filteredMessages + ' , ' + lastMsg),
// success: function(res) {
// alert(res);
// }
// error: function(res) {
// alert('shit happens');
// }
});
}
$("#chatbot-submit").click(
function(){
AjaxFormRequest(null, $("#chatForm").attr("action"));
// e.preventDefault();
// return false;
}
)
});
Answer the question
In order to leave comments, you need to log in
What the hell. When you call a function, you pass arguments, but they are not specified in the function itself.
Everything is much easier to implement.
$(function () {
var myForm = $('form');
myForm.on('submit', function() {
$.ajax(
// Тут отправляем AJAX запрос, очищаем поле, вставляем сообщение в чат и т.д.
);
// Чтоб страница не перезагрузилась
return false;
});
$("#chatbot-submit").on('click', function() {
myForm.submit();
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question