skip to Main Content

I created a modal and included a chatbox inside.

But when I click on the button sent the page is reloaded: That’s I do not want. Just stay inside the modal

I think I am close but I do not know exactly where is my error. Is it inside the html code or inside the javscript. I think the click is not identified, that’s why my page is reloaded.

Thank you

There my html code

      $content = '<!--  start -->';
      $content .= '<a href="#" data-bs-toggle="modal" data-bs-target="#staticBackdrop">' .  $this->app->getDef('text_gpt') . '</a>';
      $content .= '<!-- The Modal -->';
      $content .= '<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">';
      $content .= '<div class="modal-dialog modal-lg">';
      $content .= '<div class="modal-content">';
      $content .= '<!-- Modal Header -->';
      $content .= '<div class="modal-header">';
      $content .= '<h4 class="modal-title">Chat Box</h4>';
      $content .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>';
      $content .= '</div>';
      $content .= '<!-- Modal body -->';
      $content .= '<div class="modal-body">';
      $content .= '<div class="chat-box">';
      $content .= '<div class="chat-box-header">';
      $content .= '<span class="col-md-10">';
      $content .=  '<input type="text" id="InputGpt" placeholder="Write a message" autofocus>';
      $content .= '</span>';
      $content .= '<span class="col-md-2">';
      $content .= '<div class="chats" id="chats"></div>';
      $content .= '<button id="ChatGptButton">Send</button>';
      $content .= '</span>';
      $content .= '</div>';
      $content .= '<div class="chat-box-body">';
      $content .= '<div class="chat-box-message">';
      $content .= '<p class="message-text">Hello! How can I help you?</p>';
      $content .= '</div>';
      $content .= '</div>';
      $content .= '</div>';
      $content .= '</div>';
      $content .= '</div>';
      $content .= '</div>';
      $content .= '</div>';
      echo $content;

below My javascript used

const input = document.getElementById('InputGpt')
const send = document.getElementById('ChatGptButton')
const chatContainer = document.getElementById('chats')

send.onclick = () => {
    if(input.value){
        const message = `
            <div class="message">
                <div>
                    ${input.value}
                </div>
            </div>
        `
        chatContainer.innerHTML += message
        scrollDown();
        bot()
        input.value = null
    }
}

// when click enter
input.addEventListener("keypress", function(e){
    if(e.key === "Enter"){
        e.preventDefault();
        send.click();
    }
})

// scroll down when new message added
function scrollDown(){
    chatContainer.scrollTop = chatContainer.scrollHeight;
}

// bot response
function bot(){
    var http = new XMLHttpRequest()
    var data = new FormData()
    data.append('prompt', input.value)
    http.open('POST', 'ajax/chatGpt.php', true)
    http.send(data)
    setTimeout(() => {
        chatContainer.innerHTML += `
            <div class="message response">
                <div>
                    <img src="img/preloader.gif" alt="preloader">
                </div>
            </div>
        `
        scrollDown();
    }, 1000);
    http.onload = () => {
        var response = JSON.parse(http.response)
        var replyText = processResponse(response.choices[0].text)
        var replyContainer = document.querySelectorAll('.response')
        replyContainer[replyContainer.length-1].querySelector('div').innerHTML = replyText
        scrollDown();
    }
}

function processResponse(res){
    var arr = res.split(':')
    return arr[arr.length-1]
        .replace(/(rn|r|n)/gm, '')
        .trim()
}

seems an error is there :

Uncaught TypeError: chatContainer is null
    onclick https://domain/admin/script.js:14 //         chatContainer.innerHTML += message
    EventHandlerNonNull* https://domain/admin/script.js:5 //send.onclick = () => {


send.onclick = () => {
    if(input.value){
        const message = `
            <div class="message">
                <div>
                    ${input.value}
                </div>
            </div>
        `
        chatContainer.innerHTML += message
        scrollDown();
        bot()
        input.value = null
    }
    return false;
}

3

Answers


  1. In send.onclick function add "return false":

    send.onclick = () => {
        if(input.value){
            const message = `
                <div class="message">
                    <div>
                        ${input.value}
                    </div>
                </div>
            `
            chatContainer.innerHTML += message
            scrollDown();
            bot()
            input.value = null
        }
        return false;
    }
    
    Login or Signup to reply.
  2. Maybe you forgot to wrap javascript in the DOM load check?
    Add your JS code to:

    <script>    
    $(document).ready(function() {
      // Your JS code...
    });
    </script>
    
    Login or Signup to reply.
  3. You could use "preventDefault" when the "send" button is clicked:

    send.onclick = (event) => {
        event.preventDefault();
        /* your if(input.value){ } here */
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search