2017-11-14 13 views
8

シンプルJSというスクリプトがチャットボットとして動作することがわかりました。 JSは、DB内lastUserMessageを検索するために、そこからbotMessageを提供する場合lastUserMessageの結果は、私が達成しようとしています何JS関数内のMySQL選択結果

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

のような定義済みのインラインいるスクリプト自体で です。

私はそれが難しいはずはないと確信していますが、それを行う方法を理解できません。ここで

JSコードです:ここでは

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 = ""; 
} 

HTMLコードが起こるのに必要なもの

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

のですか?

理想的には、スクリプトは2列 "lastUserMessage" と "botMessage" を持っているDBから値 "lastUserMessage" と "botMessage" を取る必要があります。

私がやったことは、以下のゴーストのコメントに従っていることです...しかし動作しませんでした。

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 = ""; 
} 

そしてDB_query.phpで、私は

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

がありますか? – VTodorov

+0

クライアントサイドのJSを使っていると思いますので、サーバーサイドのアプリはどのように見えますか?クライアント側のJSはサーバーへのHTTP要求を実行し、サーバーはクエリを使用してデータベースを調べます。私はJSが直接MySQLクエリを発行する場所を見ることができません。 –

+0

これはWindowsサーバー上にあります。 JSはMySQLのクエリを発行しません....私はこれが私が起こる必要があると信じています。 – lStoilov

答えて

1

これは、私はそれがステイモスヘルプ

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 = "Sorry, Didnt get that"; //the default message 
 

 
    $.ajax({ 
 
    url: "appi.php?lastUserMessage=" + lastUserMessage, 
 
    type: "GET", 
 
    async: false, 
 
    success: function(data) { 
 

 
     var obj = JSON.parse(data); 
 

 
     if (lastUserMessage === obj.lastUserMessage) { 
 
     botMessage = obj.botMessage; 
 
     } 
 
    } 
 
    }); 
 

 
} 
 

 
//**************************************************************** 
 

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

 
//text to Speech 
 
//https://developers.google.com/web/updates/2014/01/Web-apps-that-talk-Introduction-to-the-Speech-Synthesis-API 
 
function Speech(say) { 
 
    //if ('speechSynthesis' in window && talking) { 
 
    // var utterance = new SpeechSynthesisUtterance(say); 
 
    //msg.voice = voices[10]; // Note: some voices don't support altering params 
 
    //msg.voiceURI = 'native'; 
 
    //utterance.volume = 1; // 0 to 1 
 
    //utterance.rate = 0.1; // 0.1 to 10 
 
    //utterance.pitch = 1; //0 to 2 
 
    //utterance.text = 'Hello World'; 
 
    //utterance.lang = 'en-US'; 
 
    // speechSynthesis.speak(utterance); 
 
    // } 
 
} 
 

 
//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 = ""; 
 
}
body { 
 
    font: 15px arial, sans-serif; 
 
    background-color: #fff; 
 
    padding-top: 15px; 
 
    padding-bottom: 15px; 
 
} 
 

 
#bodybox { 
 
    margin: auto; 
 
    max-width: 550px; 
 
    font: 15px arial, sans-serif; 
 
    background-color: lightgrey; 
 
    border-style: solid; 
 
    border-width: 1px; 
 
    padding-top: 20px; 
 
    padding-bottom: 25px; 
 
    padding-right: 25px; 
 
    padding-left: 25px; 
 
    box-shadow: 5px 5px 5px grey; 
 
    border-radius: 15px; 
 
} 
 

 
#chatborder { 
 
    border-style: solid; 
 
    background-color: #f6f9f6; 
 
    border-width: 3px; 
 
    margin-top: 20px; 
 
    margin-bottom: 20px; 
 
    margin-left: 20px; 
 
    margin-right: 20px; 
 
    padding-top: 10px; 
 
    padding-bottom: 15px; 
 
    padding-right: 20px; 
 
    padding-left: 15px; 
 
    border-radius: 15px; 
 
} 
 

 
.chatlog { 
 
    font: 15px arial, sans-serif; 
 
} 
 

 
#chatbox { 
 
    font: 17px arial, sans-serif; 
 
    //height: 22px; 
 
    width: 100%; 
 
} 
 

 
h1 { 
 
    margin: auto; 
 
} 
 

 
pre { 
 
    background-color: #f0f0f0; 
 
    margin-left: 20px; 
 
}
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> 
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> 
 
</script> 
 
<div id='bodybox'> 
 
    <h1>Virtual Assistant</h1> 
 
    <div id='chatborder' class="form-group"> 
 
    <p id="chatlog7" class="chatlog">&nbsp;</p> 
 
    <p id="chatlog6" class="chatlog">&nbsp;</p> 
 
    <p id="chatlog5" class="chatlog">&nbsp;</p> 
 
    <p id="chatlog4" class="chatlog">&nbsp;</p> 
 
    <p id="chatlog3" class="chatlog">&nbsp;</p> 
 
    <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()" class="form-control"> 
 
    </div>

で動作させる方法です

とappi.phpに私はこれが実行されているどのようなサーバーにこのコード

$p = $_GET['lastUserMessage']; 
//open connection to mysql db 
$connection = mysqli_connect("localhost","username","password","dbname"); 

//fetch table rows from mysql db 
$sql = "select lastUserMessage, botMessage FROM `table_name` WHERE lastUserMessage='$p'"; 
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection)); 

//create an array 

$emparray = $array; 
while($row =mysqli_fetch_assoc($result)) 
{ 
    $emparray = $row; 
} 
echo json_encode($emparray); 

//close the db connection 
mysqli_close($connection); 
4

Javascriptを持っているが、クライアントのブラウザで実行されます。 MySQLはサーバ上で動作します。したがって、それらを接続するために何かが必要です。

PHPとAJAXをそれらの間のコンジットとして使用します。 JSはAJAX呼び出しを発行します。 (注: "A"は "Asynchronous"の略です。)JSは結果を "コールバック"で取得します。一方、AJAXの「呼び出し」のターゲットは、データベース(MySQL)に接続してSELECTを実行し、JSに戻すJSONを構築するPHPプログラム(JavaまたはVBなど)です。

6

現在実行しているJavascriptはブラウザで実行されますが、データを取得できるデータベースには接続されていません。

これを行うには、NodeJSを使用してJSで書かれていると仮定して、POSTまたはGETリクエストをバックエンドサーバーに送信する必要があります。あなたはNEVERは、ユーザのアクセスを与える必要があります(例えば、ブラウザで実行あなたが今使用しているコードにデータベースを接続する)彼らは、彼らがやりたいことができているように、データベースを言ったために

注意それと。

あなたはNodeJSに見てみたいとどのようにリクエストを処理する場合

は、私はあなたが db_query.php動作することを確認しているあなたが専門知識

+0

ありがとう、私はそれをやろうとしました...何らかの理由でデータベースへのリクエストをトリガーしたくない場合 – lStoilov

+0

AJAXリクエストの代わりにNodeJSを使用している場合は、websocket – Kulvar

+0

を使用することをお勧めします。これは「ExpressJS」を推奨しています。データベースにアクセスしてそのデータをクライアントに返すだけの場合は、フル機能のフレームワークを使用する理由は何ですか?またはフレームワークはまったくですか?それは始めるのが簡単かもしれませんが、私の意見では学ぶのは良い方法ではありません。 –

1

のあなたのレベルに応じて、W3Schoolsの上ExpressJSthis great MySQL + NodeJS tutorialに見てください?

URLの前にヒットするには、ChromeのようなPOSTMANまたはBroswerを使用してください。 localhost/db_query.phpまたは正しいものを探して、期待している結果が得られるかどうかを確認してください。

あなたが期待した結果を得たら、JavaScriptに何か問題があります。

$ .ajaxは非同期なので、呼び出され、JavaScriptの実行は継続されます。

私はそれを説明しようとします。あなたはchatbotResponse()魔女がsuccess

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

が、$アヤックスが非同期でデータをセットにそうjavascriptの実行を続けること$.ajaxコールを行い呼び出すSO成功する前に実行されます。このJavaScriptコードが呼び出され

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

ので、問題は上記のコードが実行される前に実行されます。db_query.php

ソリューション

簡単な解決策は、ajaxを同期呼び出しasync:falseに変更することです。これはベストプラクティスではありません。

$.ajax({          
    url: 'db_query.php?lastUserMessage='+lastUserMessage,   
    type: "GET", 
    async: false,    
    success: function(data)   
    { 
    var lastUserMessage_db = data[0]; 
    var botMessage_db= data[1]; 

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

良い方法は

例成功コールバックを利用することである:

$.ajax({ 
     url: 'db_query.php?lastUserMessage='+lastUserMessage,   
     type: "GET", 
     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]; 
     } 

     } 
    }); 
+0

両方の例を使用しようとしましたが、なんらかの理由でクエリを実行したくありません。 db_query.phpを実行しようとすると、lastUserMessageとbotMessageの両方が返されます。私が思っていることの1つは、POSTまたはGETを使用すべきかどうかをAjaxがどのように理解しているかです。またはdataType: 'json'で十分ですか? db_query.phpで私は$ p = $ _GET ['lastUserMessage']を使用します。 urlから値を取得する。 – lStoilov

+0

ajaxコールのチェックアウトを修正しました。 – Stamos

+0

コードをチェックして、いくつかのタイプミスを確認してください。クロームのような開発ツールを使用してコードをデバッグすることをお勧めします。 – Stamos