Thursday, November 23, 2017

MySQL select result inside JS function

Leave a Comment

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

3 Answers

Answers 1

The Javascript you are executing currently runs in the browser but is not connected to any Database that you could fetch data from.

To do so you'd have to send a POST or GET request to your backend server (assuming you have one) that, I assume, is written in JS, using NodeJS.

Note that you should NEVER give the user access (e.g. connect the database to the code you are using right now, which executes in a browser) to said database as they are then able to do whatever they want with it.

If you want to look into NodeJS and how to handle requests, I suggest you look into ExpressJS and this great MySQL + NodeJS tutorial on W3Schools depending on your level of expertise

Answers 2

Javascript runs in the Client's browser. MySQL runs in the Server. So, something else is needed to connect them.

I use PHP and AJAX as the conduit between them. JS issues an AJAX call. (Note: "A" stands for "Asynchronous".) Then JS gets the results via a "callback". Meanwhile, the target of the AJAX 'call' is a PHP program (or Java or VB or ...) which connects to the database (MySQL) and performs the SELECT and builds the JSON to deliver back to JS.

Answers 3

have you confirmed that the db_query.php works?

Try to use POSTMAN or Broswer like Chrome to hit the url ex. localhost/db_query.php or the correct one and see if you get the result you are expecting.

If you get the expected result then something is wrong with you JavaScript.

$.ajax is asynchronous so it will be called and the javascript execution will continue.

I try explain it. You call chatbotResponse() witch does a $.ajax call that on success sets the data

var lastUserMessage_db = data[0];  var botMessage_db= data[1]; 

BUT $.ajax is asynchronous so javascript execution will continue SO this javascript code will run before success is called

    //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];     } 

so the problem is that the above code will run before you get the lastUserMessage from db_query.php

Solution

Easy solution is change ajax to synchronous call async:false, this is not best practice.

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

Better way is to utilize the success callback

Example:

$.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;         }          //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];         }        }     }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment