DEV Community

Cover image for Build a Chatbot with PHP, MySQL and AJAX in 10 minutes
Kingsley Ubah
Kingsley Ubah

Posted on • Originally published at ubahthebuilder.tech

Build a Chatbot with PHP, MySQL and AJAX in 10 minutes

Have you ever interacted with a chatbot to carry out some routine activity, such as opening a bank account?

A chatbot is a software application which can simulate human-like online conversations with a user.

In this tutorial, we are going to build a simple chatbot which provides real-time response to some common questions. It also answers with a fallback message when an unaccounted question is asked.

Chatbot application

The code for this project can be obtained from GitHub.

Prerequisites

To build this, you are required to know a bit of the following:

  • How to write basic PHP scripts
  • How to write basic Javascript (we'll use JS for making AJAX request)

You are also required to install either WampServer or XAMPP. These distributions come bundled with services like Apache and MySQL.

If you don't know much about PHP and JavaScript then don't worry, I'll try to explain each code block with lots of comments.

Without further ado, let's dive in!

Create the bot page

First, we create the html markup for the page. Create a bot.php and create the boilerplate HTML in it.

You can generate HTML boilerplate with Emmet by typing ! followed by enter. After creating the boilerplate code, we will go ahead to create the markup for the chat page which goes inside the <body> tags:

NOTE: You can learn more about emmet shortcut commands from my Emmet article

<div id="bot">
  <div id="container">
    <div id="header">
        Online Chatbot App
    </div>

    <div id="body">
        <!-- This section will be dynamically inserted from JavaScript -->
        <div class="userSection">
          <div class="messages user-message">

          </div>
          <div class="seperator"></div>
        </div>
        <div class="botSection">
          <div class="messages bot-reply">

          </div>
          <div class="seperator"></div>
        </div>                
    </div>

    <div id="inputArea">
      <input type="text" name="messages" id="userInput" placeholder="Please enter your message here" required>
      <input type="submit" id="send" value="Send">
    </div>
  </div>
  </div>
Enter fullscreen mode Exit fullscreen mode

The page is made up of three broad sections: the header, the body and the input area. All are enclosed inside a container which itself is inside of the main bot page.

The header area holds the heading text for the chat app.

The body section will hold all the messages from both the user and the bot. These messages will be dynamically generated from the database, and inserted into the page using JavaScript.

The input area holds the input form which is how user messages will be collected from the front end.

Style up the page

Here goes the styling for the whole page:

@import url('https://fonts.googleapis.com/css2?family=Rubik&display=swap');

/* Center body contents, both horizontally and vertically */
body{
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: "Rubik", sans-serif;
}

/* Style the outer container. Centralize contents, both horizontally and vertically */
#bot {
  margin: 50px 0;
  height: 700px;
  width: 450px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 3px 3px 15px rgba(0, 0, 0, 0.2) ;
  border-radius: 20px;
}

/* Make container slightly rounded. Set height and width to 90 percent of .bots' */
#container {
  height: 90%;
  border-radius: 6px;
  width: 90%;
  background: #F3F4F6;
}

/* Style header section */
#header {
  width: 100%;
  height: 10%;
  border-radius: 6px;
  background: #3B82F6;
  color: white;
  text-align: center;
  font-size: 2rem;
  padding-top: 12px;
  box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
}

/* Style body */
#body {
  width: 100%;
  height: 75%;
  background-color: #F3F4F6;
  overflow-y: auto;
}

/* Style container for user messages */
.userSection {
  width: 100%;
}

/* Seperates user message from bot reply */
.seperator {
  width: 100%;
  height: 50px;
}

/* General styling for all messages */
.messages {
  max-width: 60%;
  margin: .5rem;
  font-size: 1.2rem;
  padding: .5rem;
  border-radius: 7px;
}

/* Targeted styling for just user messages */
.user-message {
  margin-top: 1rem;
  text-align: left;
  background: #3B82F6;
  color: white;
  float: left;
}

/* Targeted styling for just bot messages */
.bot-reply {
  text-align: right;
  background: #E5E7EB;
  margin-top: 1rem;
  float: right;
  color: black;
  box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
}

/* Style the input area */
#inputArea {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 10%;
  padding: 1rem;
  background: transparent;
}

/* Style the text input */
#userInput {
  height: 20px;
  width: 80%;
  background-color: white;
  border-radius: 6px;
  padding: 1rem;
  font-size: 1rem;
  border: none;
  outline: none;
  box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
}

/* Style send button */
#send {
  height: 50px;
  padding: .5rem;
  font-size: 1rem;
  text-align: center;
  width: 20%;
  color: white;
  background: #3B82F6;
  cursor: pointer;
  border: none;
  border-radius: 6px;
  box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
}
Enter fullscreen mode Exit fullscreen mode

Create the query script (in PHP)

In this section, we will create the PHP script responsible for handling AJAX requests, connecting to the database and retrieving corresponding reply.

Before proceeding, we can go on and change out HTML file to .php. So if you named your page bot.html, you can change it to bot.php.

Now, please proceed to create a new .php file, and type the following code into it:

<?php

/* Establishes a connection with database. First argument is the server name, second is the username for database, third is password (blank for me) and final is the database name 
*/
$conn = mysqli_connect("localhost","root","","onlinebot");

// If connection is established succesfully
if($conn)
{
     // Get users message from request object and escape characters
    $user_messages = mysqli_real_escape_string($conn, $_POST['messageValue']);

    // create SQL query for retrieving corresponding reply
    $query = "SELECT * FROM chatbot WHERE messages LIKE '%$user_messages%'";

     // Execute query on connected database using the SQL query
     $makeQuery = mysqli_query($conn, $query);

    if(mysqli_num_rows($makeQuery) > 0) 
    {

        // Get result
        $result = mysqli_fetch_assoc($makeQuery);

        // Echo only the response column
        echo $result['response'];
    }else{

        // Otherwise, echo this message
        echo "Sorry, I can't understand you.";
    }
}else {

    // If connection fails to establish, echo an error message
    echo "Connection failed" . mysqli_connect_errno();
}
?>
Enter fullscreen mode Exit fullscreen mode

From the front-end, we will make POST AJAX queries to this script.

Create chatbot replies in MySQL database

The PHP script is ready. Next step is to add messages to the database. With WAMP and XAMPP, you have access to the phpMyAdmin GUI tool, which helps you manage your database in an easy way.

To open it, use the following link: http://localhost/phpmyadmin/index.php. You will be prompted to input your username, password and database, which by default are "root", blank, and MySQL respectively.

Once inside, create a new database using whatever name you prefer. Then create a table within the database.

Proceed to create the following fields in it:

  • id (auto incrementing): This holds the unique id for each record
  • messages: This is the field for user messages
  • replies: This is the field for all corresponding replies

Try to add as many messages as possible (to make it more fun). Your table should look similar to this:

chatbot mysql database

Make AJAX request from JavaScript and insert messages

With all the data present in the database, and the PHP script written, the last step would be to make the AJAX request from our front-end and insert new messages from both the user and bot, all using JavaScript.

Inside your front-end code (bot.html), open a script tag and write the following scripts:

<script type="text/javascript">

      // When send button gets clicked
      document.querySelector("#send").addEventListener("click", async () => {

        // create new request object. get user message
        let xhr = new XMLHttpRequest();
        var userMessage = document.querySelector("#userInput").value


        // create html to hold user message. 
        let userHtml = '<div class="userSection">'+'<div class="messages user-message">'+userMessage+'</div>'+
        '<div class="seperator"></div>'+'</div>'


        // insert user message into the page
        document.querySelector('#body').innerHTML+= userHtml;

        // open a post request to server script. pass user message as parameter 
        xhr.open("POST", "query.php");
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(`messageValue=${userMessage}`);


        // When response is returned, get reply text into HTML and insert in page
        xhr.onload = function () {
            let botHtml = '<div class="botSection">'+'<div class="messages bot-reply">'+this.responseText+'</div>'+
            '<div class="seperator"></div>'+'</div>'

            document.querySelector('#body').innerHTML+= botHtml;
        }

      })

  </script>
Enter fullscreen mode Exit fullscreen mode

Now when the send button is clicked, the users message is first retrieved and inserted into the page. Then an AJAX request is sent to the server script to retrieve the corresponding reply.

When the server responds, the response text (bot reply) is then inserted into the page.

Conclusion

Tutorials are awesome for learning how to code. Here we built a chatbot with some CSS styling, made front-end AJAX calls with JavaScript, handled queries a with PHP script, and stored all messages in a MySQL database.

Hopefully, the whole tutorial didn't exceed 10 minutes!

Let me know your thoughts in the comments.

Links

Oldest comments (1)

Collapse
 
sroehrl profile image
neoan

I don't know why this still finds it's way into tutorials and libraries in 2021, but be aware that there are SQL-injection possibilities with mysqli_real_eacape_string and that preventing those would exceed the feasibility of such entry-level tutorials. Please use prepared statements whenever handling user input.