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..
Related
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
}
})
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);
Let me preface by saying that I have spent a considerable amount of time trying to figure out the solution to this problem but I have not discovered something that works. I am using node and want to share a variable between my app.js server file and a client side javascript file (demo.js).
I run node app.js to launch the server and demo.js runs in the client. I have tried using module.exports and export but when I try importing in the demo.js file or referring to the module.exports var I get errors. Maybe I'm approaching this is in the wrong way.
For example, I am trying to use the node wikipedia package to scrape data. I have the following in my app.js file:
var wikipedia = require('node-wikipedia');
wikipedia.page.data('Clifford_Brown', { content: true }, function(response) {
console.log(response);
export const response = response;
module.exports.data = response
});
In my demo.js file I have tried importing this response var and using the module.exports var but I have been unsuccessful.
Anyone have any solutions to this issue or different approaches I should take?
Browser javascript files run in the browser. node.js javascript files run on the server. You cannot directly export things from one to the other. They are on completely different computers in different locations.
It is very important for developers to understand the notion that server-side code runs on the server and client-side code runs on the browser. The two cannot directly call each other or reach the other's variables. Imagine your server is in a data center in Seattle and the browser is running on a computer in Venice.
See How to access session variables in the browser for your various choices described for a previous answer.
In a nutshell, you can have the server insert a javascript variable into the generated web page so that when the javascript runs in the web page on the browser, it can then access that variable in its own page. Or, you can create an Ajax call so the client can request data directly from the server. Or you can have the server put some data in a cookie which the Javascript in the browser can then access.
If the data is easily known by the server at the time the page is generated and you are using some sort of page template system, then it is very easy to just add a <script> tag to the generated page that defines one or more Javascript variables that contain the desired information. Then, the client-side Javascript can just refer to those variables to have access to the data.
To pass data in http there is a request message and response message and the data needs to be inside that message.
In the request you can either pass variables in the request URL
http://host_name/path?key=value
Or inside the request body or headers.
In the response you pass back variables in the response header or response body
First Example:
One way of processing a URL request from the browser explicitly while passing variables is to set up your server to render a html page with those variables embedded.
If you use a templating engine like jade, you can consume the sent variables directly into the template using res.render({ key: 'value' }) rather than using a promise based api call which would run when the user performs some action on the client.
For instance.
// SERVER setup rendering engine
app.get('/', function(req, res) {
res.render( 'index', { key: 'value' })
}
Which will render index.html to the client with the key-value pair passed to the template file used to serve up the index.html (for example jade or ejs).
Second Example:
Using axios you can set up an action to call a server api (you can also pass variables in the URL, headers or body). Using the promise pattern you can then use these variables after the server api has responded.
// CLIENT setup axios
axios.get(URL + '/getkeyvalue')
.then(function(response) {
const value = response.data.key
})
On you server using express you (this is where you would get the optional request variables mentioned above) send back response variables in the body like this.
// SERVER setup express
app.get('/getkeyvalue', function(req, res) {
res.send({ key: 'value' })
}
Note that these are simple examples.
They are too completely different systems. The best way to accomplish what you're trying to do is the create a variable in your html on the server side by stringifying your data
<script> var my_data = <%= JSON.stringify(data) %> </script>
Thats an example using ejs, a common templating language in expressjs
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.
I have very strange problem and that problem occurs very rarely and that too in our production env.
The production env. setup is,
Apache Web Server as front layer
Apache Tomcat 6.0 as application server (liked with Apache Web server via mod_jk)
I have custom made Ajax based RPC component where we use jQuery for ajax calling. The data is communicated using POST method.
The client side data (javascript objects) are sent to server in JSON format and on server side they are deserialized into java objects.
The RPC call is executed by providing following information,
var jsonParamObj = new Object();
jsonParamObj.param0 = objParam0;
var params = new Object();
params.**jsontext**=**toJsonString**(jsonParamObj);
where jsontext contains the real data to be transmitted. I am using toJsonString javascript function available as open source json script (previously used JSON.stringify but had same problem).
Following is the jQuery call,
$.ajax({async:async,
data:params,
dataType:"json",
type:"POST",
url:this.ajaxAction+qs,
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
error:function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Connectivity Issue : '+textStatus + ' Error : '+errorThrown + ' Response : '+XMLHttpRequest.responseText);
},
success:function(jsonobj){
if(jsonobj.JSON.ajaxSysError)
{
alert(jsonobj.JSON.ajaxSysError.message);
return;
}
// do other work
}
});
Now the problem is sometimes whatever data sent in forms of params do not reach to server (not to apache as well as tomcat) I have enabled maximum level of verbosity in logs however whatever data it sends through query string (see qs) reaches server.
The client browser is IE 7 (Windows XP Media Edition).
Can you put some thoughts that would help me in debug this issue.
Thanks for reading this long question.
Jatan
Install Fiddler and look at the HTTP request that IE is sending.
Also, put the ajax call in a try/catch block and check whether you're getting any Javascript errors.