0

As I'm developing one chat bot for booking bus tickets I get request from user manually and returned response based on user request from API I did almost but I have doubt while passing returned data from Python to JavaScript using my IP address. Please anyone help me.

Here is my py:

import requests,json
import requests, json
from flask import render_template
import os
import time
from flask import render_template, Flask, request
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
# # import win32api
#
# win32api.MessageBox(0, 'hello', 'title')
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def map():
    return render_template("sara.html")

@app.route('/run',methods=['GET','POST'])
def main():
    print("run")
    url = 'http://webapi.i2space.co.in/Buses/Sources'
    payload = {'some': 'data'}
    headers = {'consumerkey': 'D0106432CD19C98E0E8267EDFE9E3DF0', 'consumersecret': '43DEC493EBAE756BF7A2312F55FE5132'}
    r = requests.get(url, data=json.dumps(payload), headers=headers)
    print(r.text)
    # response_data = r.json()
    response_data = json.loads(r.text)
    # print(type(response_data))
    # s=(response_data[0]['Name'])
    # print(s)
    sorceid=request.args.get('sid')
    print(sorceid)
    l=''
    for a in response_data:
        print("hello")
        print(a)
        print(a['Name'])
        if (sorceid==a['Name']):
            l=a['Id']
            print(l)
            break
        else:
            print("no")
        # list={"iden":l}
        # print(list)
    return render_template("sara.html",l=l)

if __name__ == '__main__':
   app.run(host='192.168.1.80')

Here is my JavaScript:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="/static/style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  </head>
  <body>
  <h1> HERE COMES!!!</h1>
  {{ l }}

<div class="w3-container w3-teal" align="center" style="width: 50%">
  <span>Bus-Bot</span>
</div>

 <div class="w3-container" align="center" style="width: 50%">

      <div id="chatbox">
       <p class="botText"> Bus-Bot:<span>Hi! I'm Bus-Bot.</span></p>
      </div>
      <div id="userInput">
          <input id="textInput" type="text" name="msg">
        <input id="buttonInput" type="submit" value="submit" >
      </div>

      <script>
        function getBotResponse() {
          var rawText = $("#textInput").val();
          var userHtml = '<div id="Chatid" class="container">'+
              '<p class="userText" >ME:<span>' + rawText + '</span></p>'+'</div>';
          $("#chatbox").append(userHtml);
          document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
        $.get("run", { msg: rawText }).done(function (data) {
              alert(data);
              var sou=data.l;
              alert(sou);
              alert(lol);
            var botHtml = '<div id="botcon" class="container darker">'+'<p class="botText">Bus-Bot:<span>' + sou + '</span></p>'+'</div>';
            console.log(botHtml);
            $("#botcon").append(botHtml);
            document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
          });


        }
        $("#textInput").keypress(function(e) {
            if(e.which == 13) {
                getBotResponse();
            }
        });$("#lolInput").keypress(function(e) {
            if(e.which == 13) {
                alert('weldone');
                getBotResponse();
            }
        });
        $("#buttonInput").click(function() {
          getBotResponse();
        })
      </script>
     <style>
         .container {
    border: 2px solid #dedede;
    background-color: #f1f1f1;
    border-radius: 5px;
    padding: 10px;
    margin: 10px 0;
}

/* Darker chat container */
.darker {
    border-color: #ccc;
    background-color: #ddd;
}

/* Clear floats */
.container::after {
    content: "";
    clear: both;
    display: table;
}

/* Style images */
.container img {
    float: left;
    max-width: 60px;
    width: 100%;
    margin-right: 20px;
    border-radius: 50%;
}

/* Style the right image */
.container img.right {
    float: right;
    margin-left: 20px;
    margin-right:0;
}

/* Style time text */
.time-right {
    float: right;
    color: #aaa;
}

/* Style time text */
.time-left {
    float: left;
    color: #999;
}
     </style>

 </div>
    </div>

  </body>
</html>

From Python I returned response using variable name "l" but I don't know how to pass this variable to JavaScript I want to get my response below to this line

var botHtml = '<div id="botcon" class="container darker">'+'<p class="botText">Bus-Bot:<span>' + sou + '</span></p>'+'</div>'; 

1 Answer 1

1

The render_template function from Flask doesn't pass any variable from one language to the other. It just replaces strings inside the html-template that it finds with a variable that you handover to it. With

return render_template("sara.html",l=l)

you are telling the program to take the sara.html template and insert your variable l anywhere where it finds {{ l }} in the template. You should see it in the actual HTML that you are sending to the client. because you are inserting it under your heading:

<h1> HERE COMES!!!</h1>
  {{ l }}

It is really more helpful if you are using it to render pure HTML and not JavaScript. Of cause you can also replace things inside your JavaScript but that is really not a sensible way to do client-server communication. If you want communication between your client and server you should think about a different architecture.

Doing the get call

url = 'http://webapi.i2space.co.in/Buses/Sources'
payload = {'some': 'data'}
headers = {'consumerkey': 'D0106432CD19C98E0E8267EDFE9E3DF0', 'consumersecret': '43DEC493EBAE756BF7A2312F55FE5132'}
r = requests.get(url, data=json.dumps(payload), headers=headers)

inside your server is probably better kept in your client-side Javascript.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.