B
B
baomastr2016-08-08 12:13:05
JavaScript
baomastr, 2016-08-08 12:13:05

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;
        }
    )
});


here is the whole code

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin B., 2016-08-08
@baomastr

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();
  });

});

R
riot26, 2016-08-08
@riot26

https://stackoverflow.com/questions/23507608/form-...

V
Vladimir Kulikov, 2021-10-01
@it_proger29

<form onsubmit="return false;">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question