How to integrate python chatbot to a website - javascript

I have created a chatbot in python. I have also created a UI in html, css and js and connected the python chatbot to ui using flask. This is how it looks.
UI Image
How to flow goes is when a user inputs in the chat ui, the content is sent to flask and from flask to python file. The python file provides a response to flask app which passes the response to ui file where it is shown.
Now, the question is I have a different website and I want to integrate the UI created to this website. How can I do this?

So, if you have the front-end and back-end separately, then what you have to do, is make request to your back-end that runs on a separate server and the front-end on other. Since you are using flask, this might be the sample of route:
#app.route("/chat")
def chat():
message = request.args["message"]
reply = "Something to reply"
return reply
Then, in the front-end you can make requests with JQuery
$.ajax({
type: "GET",
url: "yourdomain.com/chat"
data: {
message: "The message from the client side"
},
success: (data)=> {
// do something with the reply here
}
})

Related

How to call a function written in C with axios?

I’ve used a microcontroller to develop the embedded web server and I’m not sure if I can download an Apache or any other server into my controller.
However, I’ve successfully implemented an HTTP interface and have been hosting web pages and handling & parsing the POST request data/payload at the embedded web server side.
The issue is coming when the web page contains any form type data to be submitted.
I receive the value(s) entered by the user on the web page but I'm not able to display the data properly on the web page sent by the embedded server.
That’s where there’s a major issue in linking C (freeRTOS) code (server side) and JS (client side).
How can a JS web client pull data from embedded web server (in freeRTOS) given that I have a successful HTTP connection established with the web page and I'm also able to host pages as mentioned above?
Currently I'm using axios but unable to figure out how to call a C function in the URL? As it's not possible to code in C without a function.
axios({
method: 'post',
url: 'getStatus.c',
data: sampleData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
console.log(response);
})
You cannot directly call a function in uncompiled C source file.
axios is a client side ( JS lib ) technology. Any server side program that you want to interact with axios must implement some sort of HTTP interface.
If you must use C to achieve something like that:
Implement a CGI interface in C
CGI program can as simple as something like this ( Handling POST request is bit more difficult ):
#include <stdio.h>
int main()
{
printf("Content-type: text/html\n\n");
printf("<html>\n");
printf("<body>\n");
printf("<h1>Hello there!</h1>\n");
printf("</body>\n");
printf("</html>\n");
return 0;
}
You can access POST request data the following way:
len_ = getenv("CONTENT_LENGTH");
len = strtol(len_, NULL, 10);
postdata = malloc(len + 1);
if (!postdata) { /* handle error or */ exit(EXIT_FAILURE); }
fgets(postdata, len + 1, stdin);
/* work with postdata */
free(postdata);
How to retrieve form "POST" data via cgi-bin program written in C
More on CGI C programs: http://jkorpela.fi/forms/cgic.html
Consider using libcgi http://libcgi.sourceforge.net for CGI C programs.
Compile the CGI program.
Use Apache2 or Nginx to serve the CGI "script" in this case the compiled binary.
If using C is not a priority:
I would recommend to use a high level language which is more suitable for web development. Python / PHP / C# / Java / etc..

How to execute Python code from Javascript for dummies

I'm looking for an answer to this question that frames the issue for someone who doesn't really understand http requests and is attempting this for the first time.
I wanted to make a simple html web application for running an online experiment. Right now we don't have a server and we're just trying to make a prototype that functions on a local machine offline. I'm using a javascript framework for behavioral experiments that makes things easier, but I have this block of code indicating that want a python script called "create_stimuli.py" to execute its main function upon finishing the trial. I was hoping to pass one parameter collected from a form, the number of trials, to this python script.
var creating_stimuli = {
type: "html-keyboard-response",
stimulus: "<p>Stimuli for this trial will be initialized upon continuing and experiment session with user will begin</p>" +
"<p>Closing the tab or window for this experiment will result in data loss. Reaction times will be measured</p>",
prompt: "press any key to continue",
on_finish: function(data){
$.ajax({
url: "/Scripts/create_stimuli.py",
type: "POST",
//I do need to pass in a parameter
success: function(response) {
//manipulate response variable here
}
})
}
}
My python file doesn't have any special conventions at the moment, it's just like a regular python program - it just has some import statements at the top. I'm not sure if I need something else.
The error message I get for executing this javascript is the following.
jquery.min.js:2 Access to XMLHttpRequest at 'file:///D:/Scripts/create_stimuli.py' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I genuinely don't quite understand what this error message means, though I can at least take the hint that I wasn't using protocol schemes correctly at all. And I'm not sure how to edit my javascript code to get it in the right direction.
From google searching, I find approaches that use Flask, AJAX, XMLHttpRequests, CGI and other approaches... Other than the fact that I need AJAX, I can't tell which tools I actually need to accomplish. Do I really need a whole web development framework like Flask just to execute a python script from Javascript?
Here's how you do it. This will give a quickstart for anyone intending to do behavioral experiments in JsPsych. The following code will allow you to pass in js variables using an AJAX call from Javascript to a python script. This logs a variable for number of trials in the console. if calling the script fails, an alert box is shown instead.
These links are helpful, particularly becasue the first talks about the potential importance of using an __init__.py script and organizing flask in a more modular way like how flask documentation actually does
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-a-better-application-structure
It is best to create a simple __init__.py that can reliably boot/work without bugs. Your __init__.py program probably need to be able to be able to handle the url request of "/", the home page for your app. __init__.py also needs to register the blueprint variable created for whatever python program you intend to execute "remotely" from javascript/via AJAX. In that Here's what that __init__.py function might look like.
import os
from flask import Flask
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True) # creates the flask instance
app.config.from_mapping(
SECRET_KEY='dev',
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
from . import experiment // from '.' or this current directory, import the python program/module entitled "experiment.py"
app.register_blueprint(experiment.bp) // register the blueprint variable created in experiment.py
app.add_url_rule('/', endpoint='index') //requests the url associated with '/'
return app
I created a python program called experiment.py, it lives in the same directory as __init__.py. Both of these scripts are at the topmost level of this flask application directory structure, I'm following the structure in the blog post I included (and again, what's in Flask documentation)
experiment.py servers the same purpose as app.py, which is what people used to commonly refer to scripts containing view functions/python code to execute (if I got the terminology right)
Anyways, experiment.py needs to use blueprint.route('/url_path') to mount python "view functions" to particular urls that can be requested. You also need to return "render_template('index.html')" to return the html for the homepage (but you technically can return anything else.
This is what experiment.py looks like
import functools
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash
bp= Blueprint('experiment', __name__)
#bp.route('/')
def index():
return render_template("index.html")
#bp.route('/testing', methods=['GET', 'POST'])
def testing_func():
trial_num = request.form['trials']
return trial_num
In your jS script, if you just use an AJAX script containing a dictionary/JSON dictionary, it gets embedded into a flask request object in the "form" parameter as form data. You can access data parameterized in a field, "data" (that lives in the AJAX script) in python using request.form['key_name']
For JS (and if you're using the jspsych framework, the AJAX request might look like.
var creating_stimuli = {
type: "html-keyboard-response",
stimulus: "<p>Stimuli for this trial will be initialized upon continuing and experiment session with user will begin</p>" +
"<p>Closing the tab or window for this experiment will result in data loss. Reaction times will be measured</p>",
prompt: "press any key to continue",
on_finish: function(data){
$.ajax({
type: "POST", // declaring AJAX post request
url: "/testing", //Needs to go to the url mounted
data: {
trials:100
},
success: function(response) {
console.log(response);
},
error: function(xhr, textStatus, thrownError) {
alert('err');
}
});
}
}
timeline_arr.push(creating_stimuli);

Execute php code on different server via javascript

As part of my third year project for university I am creating a HTML5 Web App for the amazon fire tv OS. This web app is supposed to communicate with another remote server to update another client with information about what the user is currently watching. I have succesfully implemented this communication using socket.io on localhost but unfortunately the android OS does not support web sockets, so I cannot use socket.io within the fire tv app itself.
To get around this I thought about having a php file on my server that will emit the socket request when a relevant GET request for the page is requested. The php code for the file is below:
if(isset($_GET['title'])){
echo "
socket.emit('vidStart', '" . $_GET['title'] . "');
";
}
echo "</script>";
As you can see all the code does is emit when the page is requested using a title parameter.
Now, this works fine when I go to the web browser myself and enter the url, the emit succeeds and my server receives the message.
However, I am trying to execute this on the server remotely using javascript, to get around having to use socket.io in my fire os app.
The code I currently have in my app is below:
$.ajax({
'type': 'GET',
'url': 'http://138.68.175.172:81',
'data': 'title=example',
success: function(response){
console.log(response);
}
});
This returns the correct response but doesnt seem to actually execute the php code and emit via socket io on my server. My question is, is this possible to do via javascript and php? I have tried looking at XMLWebRequest but it seems to do the same thing, and responds with the web page.
If this isn't possible, is there any other way to send information to a remote server, and have it execute a command ( in this case emit a socket.io message)?

Consume PHP web service with javascript (client side programming) Sharepoint

I'm not familiar with Web Services. My company wants to integrate SharePoint 2013 to SAP. My company (right now) only allow us to develop SharePoint app using client side programming (JavaScript).
We already have some PHP application connect to SAP through RFC, so my idea is creating PHP web service and consume it from JavaScript (SharePoint).
My Question :
1. Can we do that?
2. Is there another ways to integrate SP to SAP with Client Side Programming?
I tried simple JavaScript calling php function (not a webservice) using Ajax below, but having error (alert:error2).
$.ajax({
type : "POST",
url : "http://10.15.5.150/testapp/test_ws",
data : "id=1",
cache : false,
success : function(data){
var data = eval('('+data+')');
if(data.success){
alert(data.msg);
}else{
alert('error');
}
},
error: function(data){
alert('error2');
}
});
Thanks.
Consuming a PHP web service is most definitely possible with having javascript as a client. It is especially simple if you can make use of the JQuery library in javascript. This Library will give you simple tools you need to create ajax requests to the PHP service.
If the PHP Web Service is hosted on another domain, (Other than the SharePoint domain) the SharePoint server providing the Javascript needs to include the following header.
"Access-Control-Allow-Origin: <domain-of-php>"
Note: the domain can also be * for all domains.
This header will allow the browser to connect to other domains other than the original domain.

How to integrate mailchimp using javascript

I have a web app and I will like to integrate mailchimp such that when a user clicks the signup button on the page, the user's email is added to a mailchimp subscription list but I'm having difficulty in doing so. The problem is, the button on the page is created in a javascript file using extjs. I do not have that much experience in developing web applications . I already downloaded the api for integrating with php. I saw this: " AJAX Mailchimp signup form integration " but it seems to have security issues.
Can anyone help explain how to go about this?
Have the ajax call directed to your server, with the user's email.
From there, use the API (you downloaded) to add the email, and return the outcome of their response to your client.
When you do it behind the scenes (your server to theirs), there is no security risk, as you are not exposing your API key.
Client side code:
Ext.Ajax.request({
url: 'add_mail_to_chimp.php',
params: {
email: theUser_sEmail
},
success: function(response){
var text = response.responseText;
alert ('yay' + text);
}
});

Categories

Resources