'Web Chat - Writing and fetching new messages from database

I'm trying to create a web chat where clients (identified by client number) can talk to one of 4 departments in a company.

I want to use a table named Chat in my SQL database, like this:

Chat Table

Client Department Tx Rx Message Date Time
000000000 department_1 0 1 bla bla bla dd-mm-yyyy hh:mm:ss
000000000 department_1 1 0 bla bla bla dd-mm-yyyy hh:mm:ss
000000000 department_2 0 1 bla bla bla dd-mm-yyyy hh:mm:ss
000000000 department_2 1 0 bla bla bla dd-mm-yyyy hh:mm:ss
000000000 department_3 0 1 bla bla bla dd-mm-yyyy hh:mm:ss
000000000 department_3 1 0 bla bla bla dd-mm-yyyy hh:mm:ss
000000000 department_4 0 1 bla bla bla dd-mm-yyyy hh:mm:ss
000000000 department_4 1 0 bla bla bla dd-mm-yyyy hh:mm:ss

This is what I did so far on HTML:

<div id="chat">
  <div id="messages">
    <div class="spacer"></div>
    <div class="rx_message">
      <p>example of a received message</p>
    </div>
    <div class="spacer"></div>
    <div class="tx_message">
       <p>example of a transmited message</p>
    </div>
  </div>
  <form id="send_messages">
    <input type="text" id="send_messages_text" placeholder="Aa" name="message" required/>
    <input type="submit" id="send_messages_submit" onclick="sendMessages()" value="Send"/>
  </form>
</div>

And this is what I did so far on Javacript:

function sendMessages() {
  let messages = document.getElementById('messages');
  let textInput = document.getElementById('send_messages_text');
  if (textInput.value.length === 0) {
    event.preventDefault();
  } else {
    document.getElementById('sendMessages').addEventListener('submit', function(e) { e.preventDefault(); });
    let d = new Date();
    let date = ('0' + d.getDate()).slice(-2) + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + d.getFullYear();
    let time = (d.getHours()<10?'0':'') + d.getHours() + ':' + (d.getMinutes()<10?'0':'') + d.getMinutes() + ':' + (d.getSeconds()<10?'0':'') + d.getSeconds();
    const sendMessageJSON = {
      "Client": 000000000,
      "Department": "department_1",
      "Tx": 1,
      "Rx": 0,
      "Message": textInput.value,
      "Date": date,
      "Time": time
    };
    const JSONstringify = JSON.stringify(sendMessageJSON);

    const xhttp = new XMLHttpRequest();
    xhttp.onload = function() {};
    xhttp.open('POST','json.php');
    xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhttp.send(JSONstringify);

    let spacer = document.createElement('div');
    let sendMessage = document.createElement('div');
    spacer.className = 'spacer';
    sendMessage.className = 'tx_message';
    messages.appendChild(spacer);
    messages.appendChild(sendMessage);
    sendMessage.innerHTML = textInput.value;
    textInput.value = '';
    messages.scrollTop = messages.scrollHeight;
    messages.animate({scrollTop: messages.scrollHeight});
  }
}

Right now it's only validating if textInput lenght is equal to 0, and if condition is true it's not sending anything, but what I need it to check if it's really an "empty" string or not (ex: a string with only spaces).

It's also printing the send messages into the chat window (that scrolls down after submiting to show the new message), but I need it to be able to write this into my database when a client sends a new message (JSONstringify).

Also, I need it to periodically fetch new messages from database, so I've set a timer like this:

setInterval(function(){
  receivedMessages()
}, 5000); // 5 seconds

But I need some help so I can retrieve the new received messages from database and load them into the chat window!

function receivedMessages(){
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {

    const JSONparse = JSON.parse(receivedMessageJSON);
    let spacer = document.createElement('div');
    let receivedMessage = document.createElement('div');
    spacer.className = 'spacer';
    receivedMessage.className = 'receivedMessage';
    messages.appendChild(spacer);
    messages.appendChild(receivedMessage);
    receivedMessage.innerHTML = JSONparse.message;
    messages.scrollTop = messages.scrollHeight;
    messages.animate({scrollTop: messages.scrollHeight});

  };
  xhttp.open('POST','json.php');
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(receivedMessageJSON);
}

How can I use AJAX and PHP to accomplish this?

Can anyone help me out please?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source