Header Ads

How to create Chatbot for website in PHP

How to create Chatbot for website in PHP: Hello Everyone! Welcome to this article. If you are here you might be looking to How to create Chatbot for website in PHP. But you don’t know working with python.

Don’t panic. I’ll tell you how to create a chatbot using python. You might be thinking about how we can do this. Believe me, it’s easy to do.

How to create Chatbot for website in PHP




Have you ever interacted with a chatbot to perform routine activities, such as opening a bank account?

A chatBot is a software application that can mimic human-like online conversations with a user.

In this tutorial, we are going to create a simple chatbot that provides real-time answers to some common questions. It also responds with a fallback message when asked a number of questions.
 
 
Terms:
 
 To make it, you need to know a little bit of the following:

  •  How to write basic PHP script

  •  How to write basic JavaScript (we will use JS to request AJAX)


You also need to install WampServer or XAMPP. These partitions are bundled with services such as Apache and MySQL.

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

Without further ado, let's dive in!

 

Create a boot page:

 First, we create HTML markup for the page. Create a bot.php file and set up the boiler plate HTML in it.

You can create HTML boiler plate with Emmet by typing! After enter. After generating the boiler plate code, we will proceed to create the markup for the chat page which goes within the tags:
 
<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> 
 
The page consists of three broad sections: Header, Body and Input Area. All are enclosed in a container that is inside the main boot page itself.

The header area contains the caption text for the chat app.

The body section will contain all messages from both the user and the boot. These messages will be dynamically generated from the database or inserted into the page using the JavaScript.

The input area contains the input form as the user's messages will be collected from the front end. 
 
Style up 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);
}
 
Create query script (in PHP)
 
In this section, we will create a PHP script that is responsible for handling AJAX requests, connecting to the database, and retrieving the relevant response.

Before proceeding, we can convert the HTML file to .php. So if you have named your page bot.html, you can change it to bot.php.

Now, please 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();
}
?>

 

Create chat boot responses in the MySQL database

 
 PHP script ready. The next step is to add messages to the database. With WAMP and XAMPP, you have access to the phpMyAdmin GUI tool, which helps you easily manage your database.

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

Once logged in, create a new database using whatever name you like. Then create a table inside database.

Proceed to create the following steps in it:

  •  id (auto incrementing): It has a unique ID for each record.

  •  Messages: This is the user's message field.

  •  Answers: This is the field for all relevant answers.


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

Request AJAX from JavaScript and insert messages.


With all the data in the database, and the PHP script being written, the last step will be to request AJAX from our frontend and insert new messages from both the user and the boot, all using JavaScript. ۔

Inside your frontend code (bot.html), open a script tag and type the following script:

<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>

Now when the send button is clicked, the user's message is first retrieved and inserted into the page. An AJAX request is then sent to the server script to retrieve the same response.

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

Conclusion: 

Lessons are great for learning how to code. Here we built a chat boot with some CSS styling, made front-end AJAX calls with JavaScript, handled queries with PHP script, and saved all messages in MySQL Database.
 
 



 

 


No comments:

Powered by Blogger.