Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select result inside JS function

Tags:

People also ask

Can I fetch data from database using JavaScript?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

Can we use SQL query in js?

SQL. js is a JavaScript library that allows you to create and query a relational database entirely in the browser. It uses a virtual database file stored in the browser memory, so it doesn't persist the changes made to the database.

Can JavaScript interact with MySQL?

JavaScript MySQL Integration will make the websites and applications user interactive, allow companies user data through JavaScript MySQL connection, and manipulate data. In this article, you will have a brief introduction to MySQL Database, JavaScript, and the steps to set up JavaScript MySQL Integration.

Can js interact with database?

There is no common way to connect to SQL Server database from JavaScript client, every browser has it's own API and packages to connect to SQL Server.


I found a simple JS script that works as a chatbot. in the script itself the results of lastUserMessage are predefined inline like

if (lastUserMessage === 'name') {
   botMessage = 'My name is ' + botName;
}

What I am trying to achieve is if the JS to search for lastUserMessage within a db and to provide botMessage from there.

I am sure it should't be that hard, but I cant figure out how to do it.

Here is the JS code:

nlp = window.nlp_compromise;
var messages = [], //array that hold the record of each string in chat
  lastUserMessage = "", //keeps track of the most recent input string from the user
  botMessage = "", //var keeps track of what the chatbot is going to say
  botName = 'Bot Name', //name of the chatbot
  talking = true; //when false the speach function doesn't work

//edit this function to change what the chatbot says
function chatbotResponse() {
  talking = true;
  botMessage = "Ops... didn't get this"; //the default message

  if (lastUserMessage === 'name') {
    botMessage = 'My name is ' + botName;
  }

}

//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
  //if the message from the user isn't empty then run 
  if (document.getElementById("chatbox").value != "") {
    //pulls the value from the chatbox ands sets it to lastUserMessage
    lastUserMessage = document.getElementById("chatbox").value;
    //sets the chat box to be clear
    document.getElementById("chatbox").value = "";
    //adds the value of the chatbox to the array messages
    messages.push(lastUserMessage);
    //Speech(lastUserMessage);  //says what the user typed outloud
    //sets the variable botMessage in response to lastUserMessage
    chatbotResponse();
    //add the chatbot's name and message to the array messages
    messages.push("<b>" + botName + ":</b> " + botMessage);
    // says the message using the text to speech function written below
    Speech(botMessage);
    //outputs the last few array elements of messages to html
    for (var i = 1; i < 8; i++) {
      if (messages[messages.length - i])
        document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
    }
  }
}

//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if (key == 13 || key == 3) {
    //runs this function when enter is pressed
    newEntry();
  }
  if (key == 38) {
    console.log('hi')
      //document.getElementById("chatbox").value = lastUserMessage;
  }
}

//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
  document.getElementById("chatbox").placeholder = "";
}

Here is the HTML code

<div id='bodybox'>
  <div id='chatborder'>
    <p id="chatlog2" class="chatlog">&nbsp;</p>
    <p id="chatlog1" class="chatlog">&nbsp;</p>
    <input type="text" name="chat" id="chatbox" placeholder="Hi there! Type here to talk to me." onfocus="placeHolder()">
  </div>

What need to happen?

Ideally, the script should take the values "lastUserMessage" and "botMessage" from a db that has 2 columns "lastUserMessage" and "botMessage".

What I tried to to do is following Ghost's comment below... but didn't work.

    nlp = window.nlp_compromise;
var messages = [], //array that hold the record of each string in chat
  lastUserMessage = "", //keeps track of the most recent input string from the user
  botMessage = "", //var keeps track of what the chatbot is going to say
  botName = 'Bot Name', //name of the chatbot
  talking = true; //when false the speach function doesn't work

//edit this function to change what the chatbot says
function chatbotResponse() {
  talking = true;
  botMessage = "Ops... didn't get this"; //the default message

      $.ajax({                                      
  url: 'db_query.php',         
  data: "lastUserMessag=lastUserMessag", 
  dataType: 'json',                 
  success: function(data)          
  {
    var lastUserMessage_db = data[0]; 
    var botMessage_db= data[1];

if (lastUserMessage === lastUserMessage_db) {
    botMessage = botMessage_db;
  }
  } 
});

}

//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
  //if the message from the user isn't empty then run 
  if (document.getElementById("chatbox").value != "") {
    //pulls the value from the chatbox ands sets it to lastUserMessage
    lastUserMessage = document.getElementById("chatbox").value;
    //sets the chat box to be clear
    document.getElementById("chatbox").value = "";
    //adds the value of the chatbox to the array messages
    messages.push(lastUserMessage);
    //Speech(lastUserMessage);  //says what the user typed outloud
    //sets the variable botMessage in response to lastUserMessage
    chatbotResponse();
    //add the chatbot's name and message to the array messages
    messages.push("<b>" + botName + ":</b> " + botMessage);
    // says the message using the text to speech function written below
    Speech(botMessage);
    //outputs the last few array elements of messages to html
    for (var i = 1; i < 8; i++) {
      if (messages[messages.length - i])
        document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
    }
  }
}

//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if (key == 13 || key == 3) {
    //runs this function when enter is pressed
    newEntry();
  }
  if (key == 38) {
    console.log('hi')
      //document.getElementById("chatbox").value = lastUserMessage;
  }
}

//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
  document.getElementById("chatbox").placeholder = "";
}

And in DB_query.php I have

$p = $_GET['lastUserMessag']; 
      $query=mysql_query("SELECT lastUserMessag, botMessage FROM `aiml` WHERE lastUserMessag='$p'");
      $array = mysql_fetch_row($query);  
    echo json_encode($array);