Passing form data to python - javascript

I have an HTML form with data that I would like to send to my SVN. Since HTML/JS have no means of doing this, I want to use Python as a link between the form and the SVN. My problem is that I do not know how to send data from HTML/JS to Python, both of which are client side (there is no server involved).
What I imagined would happen is that a user would fill out the form, then press a 'submit' button, which would call a Python script and pass their form data as arguements.
I have been searching and found that people are running Python server side and POSTing to it from their javascript, but since I have no server I don't think this is possible for me.
Is it possible to send data from HTML/JS to Python if they are both client side?
EDIT: I should add that I do have a good background in Python and JS

Here's a few neat ways of combining Python with JavaScript:
Return data from html/js to python
Note: Since you mentioned you had no server, the request you call with the javascript has to be pointed to the listening port of the socket that the python code runs on.
Easy enouhg would be to listen on port 80 with python and just do regular calls without thinking twice to the :80 from JavaScript.
Basically, HTML form, use JavaScript onSubmit() or a button that calls the AJAX code in the post above, then have Python read the JSON data (structure the <form> data according to the JSON format shown at the top of the link)
Here's a short intro on how to use form data via javascript:
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar = form.inputbox.value;
alert ("You typed: " + TestVar);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
Use this principle to gather your information,
then build in the AJAX part in the link mentioned at the top..
Once you've done that, start a python script (shown in the link as well) that listens for these calls.
Remember: To use JSON, format it properly, ' will not be allowed for instance, it has to be "!
In my link, this is the important part that sends the GET request to the "server" (python script):
xmlhttp.open("GET","Form-data",true);
Here's the python part:
from socket import *
import json
s = socket()
s.bind(('', 80)) # <-- Since the GET request will be sent to port 80 most likely
s.listen(4)
ns, na = s.accept()
while 1:
try:
data = ns.recv(8192) # <-- Get the browser data
except:
ns.close()
s.close()
break
## ---------- NOTE ------------ ##
## "data" by default contains a bunch of HTTP headers
## You need to get rid of those and parse the HTML data,
## the best way is to either just "print data" and see
## what it contains, or just try to find a HTTP parser lib (server side)
data = json.loads(data)
print data

Related

Failing to pass data from client (JS) to server (Flask) with Ajax

First time ever using jQuery to pass a dictionary filled through a JS script to my server written in Python (Flask) when the user hits a submit button (I read somewhere that AJAX was the way to go).
Something must be broken since in the server function described below, request.get_data() or request.form are None. If any seasoned programmer could give recommendation on how to set up a jQuery request, it would be much appreciated.
In Python, I have the following:
#app.route('/submit',methods=['POST'])
def submit():
info = request.form['info']
action = request.form['action']
...
To handle the dictionary info. On my html file, I load AJAX through:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
Define my "submit" button as followed:
<button class="btn" onclick="send(event,'s')" id="SUBMIT">Submit</button>
And handle the action through the script:
<script>
var dict = [];
function send(event,action) {
$.post('/submit', {
info: dict,
action: action
}).done(function() {
}).fail(function() {
});
}
...
</script>
Convert request.form to dictionary and print it you can able get the values
print(request.form.to_dict())

How you can save appends to variables an then convert them to php so you can save them in a database?

<html>
<head>
<meta charset="utf-8">
<title>Test page for Query YQL</title>
<link rel="stylesheet" href="http://hail2u.github.io/css/natural.css">
<!--[if lt IE 9]><script src="http://hail2u.github.io/js/html5shiv.min.js"></script><![endif]-->
</head>
<body>
<h1>Test page for Query YQL</h1>
<div id="content"></div>
<input type="button" name="bt1" value="click" onclick="pesquisa()">
<form name="s2">
<input type="text" name="s1">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.query-yql.min.js"></script>
<script type="text/javascript">
function pesquisa(){
$(function () {
var t = $('#content').empty();
var url= document.s2.s1.value;
var statement = 'select * from feed where url="'+url+'"';
$.queryYQL(statement, function (data) {
$('<h2/>').text('Test: select * from feed').appendTo(t);
var r = data.query.results;
var ul = $('<ul/>');
$.each(r.item, function () {
$('<li/>').append(this.title).appendTo(ul);
$('<li/>').append(this.link).appendTo(ul);
<?php
$titulo = "<script>document.write(titulo);</script>";
$site = "<script>document.write(site);</script>";
//echo $titulo;
//echo $site;
?>
});
ul.appendTo(t);
});
});
};
</script>
</body>
</html>
How can you save the this.title and the this.link values into 2 different variables an then call them into php so you can insert the data into a DB?
It's just a simple YQL query to search on rss feeds.
After doing the query, I want the results to be saved in a database, but I can't discover how to do that.
First of all, you have to understand that you are working on a Client-Server architecture.
This means:
Let's say that this file you are showing us is called "TestYQL.php" (because you did not say the name of it). This file is executed by php (server side), which reads line by line the contents of it, and generates another new file from the original. For educational purposes, let's say the generated file is called "GeneratedTestYQL.html". This file no longer has any php code inside, since it is directly html and js flat. It knows nothing about php. So there are no php functions, variables, nothing. This last file is the one that reaches the client, and the code is executed by a web browser like Chrome, Firefox, etc.
In your case, the file "TestYQL.php" all you have of php is what is inside the <? Php ....?> Tags. With php you creates 2 variables, each with a tag inside, but without any purpose since they are not used in any way. So, the generated "GeneratedTestYQL.html" file is the same as the original, but without the lines inside the <? Php ...?>.
This means that: The contents of the variables that you use in PHP can be sent to the browser, because with PHP you will generate the file that will be executed in the browser.
Now, when the file "GeneratedTestYQL.html" arrives, the browser starts to show all the contents of the file, it generates the form in which, when you click the button, executes the function pesquisa() and now starts javascript (JQuery) bringing data of the feeds, and for the first time, these variables "this.title" and "this.link" begin to exist in javascript.
Since there is no such thing as php here, you can NOT access those variables from php.
So, how to save that data in a DB?, well, the common way is to send all the data you want from the browser, to the server, then the server sees what to do with that data. To send data from the browser to the server, you do it by making GET or POST requests to a php file from the server (preferably another file, let's say it will be called "saveFeeds.php").
Data can be sent with a GET request, but it is semantically incorrect since GET means you want to fetch data from the server. So to send that data to the server, you will have to make a POST request from the browser, which is more appropriate.
There are now 2 simple ways to make a POST request. The first and most common of these is from a form in the browser, the other way is using Ajax.
How to do it from a form?
Currently in your code, you have already put a form (That is called "s2"), although currently the same is not necessary, but leave that now.
If you wanted to send the data through a form, you should do 2 things. First and most obvious, create the form; second, the data received from the internet (title and link of feed), send them to the server.
Assuming you fetch data from a single feed per url, and the designated file in charge of receiving the request will be "saveFeeds.php". So, you could create a form like the following after the previous one:
<Form class = "sender" action = "saveFeeds.php" method = "post">
  <Input type = "hidden" name = "title" value = ""> <br>
  <Input type = "hidden" name = "link" value = ""> <br>
  <Input type = "submit">
</ Form>
Then you need to put the feed data inside the form, because, at this moment, you can't send anything. You could add a function like:
Function appendFeedToForm (title, link) {
  Var form = $ (". Sender");
  Form.title.value = title;
  Form.link.value = value;
}
And then call it from inside the $ .each of the result as
AppendFeedToForm(this.title, this.link);
The second case, the easiest way to make a request to the same file using Ajax is with a JQuery shortcut:
$.post("saveFeeds.php", r.item);
If you are interested in validations, you can take a look at the JQuery documentation. The important thing about ajax requests is that you can send all the data you want without having to force you to reload the page. Therefore, you can send as many feeds as you want in the same way you would send one.
Now with the data sent from the client to the server, it is necessary to handle the reception of the data. Currently we were pointing all the data to the file "saveFeeds.php", so, now, finally we can put the content from javascript. To access them, simply in that file, you should check the fields:
$ _POST ['title'] // This names are from input names of form
$ _POST ['link'] // or properties sended through Ajax
So, here, you have tp prepare the connection to your database and save those parameters. Currently you did not mention which database engine you are using, so, for this moment, I'll shorten the answer here.
Note: I was not giving you the best practices to solve your problem, but rather the minimum necessary.

How do I return JSON-data from python to javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm working on a pythonfile which returns the variable "distance" and sends it to a javascriptfile where I can put the value on my webpage.
My problem is that I don't know how to send the value from python to javascript. I've heard you have to make the pythonfile return in JSON-format and then make a ajax-request, but I can't find how to do it anywhere.
My question is: How do I set up the connection which makes me get the JSON-data in javascript? I would really appriciate if someone showed me using code, I'm very new to both python and javascript..
Edit:
The data comes from a RaspberryPi with a distance-sensor. My python code is:
import RPi.GPIO as GPIO
import time
import io, json
GPIO.setmode(GPIO.BCM)
TRIG = 14
ECHO = 15
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
revers = 1
while revers == 1:
GPIO.output(TRIG,0)
time.sleep(0.5)
GPIO.output(TRIG,1)
time.sleep(0.00001)
GPIO.output(TRIG,0)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
GPIO.cleanup()
I'm not yet to write anything in javascript, simply because I don't know how to make the ajax call, but my goal is to make the variable distance into JSON-format and get it up on my webpage.
The python program on your server can return any value in any format you want, but json is a convenient format, which can be readily handled by both python programs and javascript.
Your javascript needs to send a request to the server. The request will specify that it wants to retrieve the python file. Note that a javascript request is sent in reaction to some event--like the user clicking on a button.
The python program will reside somewhere in the directory structure of the server. If your server is setup correctly, then when the request for a python file is received, instead of returning the text of the python file, the server will execute the python program and return the output of the python program.
The easiest way to make an ajax (i.e. a javascript) request is with jquery. There are literally 10,000 tutorials, blogs, etc. about how to make ajax requests with jquery. Here is one:
http://www.tutorialspoint.com/jquery/jquery-ajax.htm
Here is the relevant info in the jquery docs:
https://api.jquery.com/jquery.get/
I'm very new to both python and javascript..
Then your desired program is most likely too complex.
Here is an ajax example:
page.html
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
</head>
<body>
<p>Hello</p>
<button id="my_button" type="button">Click me</button>
<div id="ajax_results"></div>
<!-- Download jquery library: -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<!-- My jquery code: -->
<script>
$("#my_button").on('click', function() {
$.get("http://localhost:8080/cgi-bin/my_prog.py", function(data) {
$("#ajax_results").text(data);
})
});
</script>
</body>
</html>
I make a request to my local server using the following url in my browser:
http://localhost:8080/page.html
which loads page.html in my browser. As the page loads, my jquery code executes, which adds an onclick handler to the button:
$("#my_button").on('click', function() {....
Thereafter, if the button is clicked, the function will execute.
The following python program resides in a directory on my local server:
my_prog.py
#!/usr/bin/env python3.4
print("Content-Type: text/html\n\n")
distance = 10
print(distance) #This is the body of the response
If I click on the button displayed in the web page, the jquery code sends a request to the server for the file my_prog.py:
$.get("http://localhost:8080/cgi-bin/my_prog.py", ....
My server is setup to execute that file--rather than return the text of the file--then the server returns the program's output as the response.
When the jquery code receives the response from the server, jquery calls the following function:
function(data) {
$("#ajax_results").text(data);
})
passing the body of the response as an argument. The function inserts the body of the response, data, into the html tag with the id "ajax_results". Because the body of the response is the string "10", 10 is displayed in the web page.

jquery prompted variable value given to python script

I have what I think to be a simple problem, but I cannot figure out the solution. I have a javascript form with options, and when the user selects an option they get prompted to input a value as below:
var integer_value = window.prompt("What is the integer value?", "defaultText")
I then need this integer value to be used by a python script. So, if say in my python script:
integer_value = 2
It would need to change to whatever value the user inputs in the prompt window.
The code below should do what you need. There may be better ways to do this, but at least this way is fairly simple.
Next time you have a Web programming question, tell us what server you're using, and what framework, and any JavaScript things like jQuery or Ajax. And post a small working demo of your code, both the HTML/JavaScript and the Python, that we can actually run so we can see exactly what you're talking about.
Firstly, here's a small HTML/JavaScript page that prompts the user for data and sends it to the server.
send_to_python.html
<!DOCTYPE html>
<html>
<head><title>Send data to Python demo</title>
<script>
function get_and_send_int()
{
var s, integer_value, default_value = 42;
s = window.prompt("What is the integer value?", default_value);
if (s==null || s=='')
{
alert('Cancelled');
return;
}
//Check that the data is an integer before sending
integer_value = parseInt(s);
if (integer_value !== +s)
{
alert(s + ' is not an integer, try again');
return;
}
//Send it as if it were a GET request.
location.href = "cgi-bin/save_js_data.py?data=" + integer_value;
}
</script>
</head>
<body>
<h4>"Send data to Python" demo</h4>
<p>This page uses JavaScript to get integer data from the user via a prompt<br>
and then sends the data to a Python script on the server.</p>
<p>Click this button to enter the integer input and send it.<br>
<input type="button" value="get & send" onclick="get_and_send_int()">
</p>
</body>
</html>
And now for the CGI Python program that receives the data and logs it to a file. A proper program would have some error checking & data validation, and a way of reporting any errors. The Python CGI module would make this task a little easier, but it's not strictly necessary.
The Web server normally looks for CGI programs in a directory called cgi-bin, and that's generally used as the program's Current Working Directory. A CGI program doesn't run in a normal terminal: its stdin and stdout are essentially connected to the Web page that invoked the program, so anything it prints gets sent back to the Web page. And (depending on the request method used) it may receive data from the page via stdin.
The program below doesn't read stdin (and will appear to hang if you try). The data is sent to it as part of the URL used to invoke the program, and the server extracts that data and puts it into an environment variable that the CGI program can access.
save_js_data.py
#! /usr/bin/env python
''' save_js_data
A simple CGI script to receive data from "send_to_python.html"
and log it to a file
'''
import sys, os, time
#MUST use CRLF in HTTP headers
CRLF = '\r\n'
#Name of the file to save the data to.
outfile = 'outfile.txt'
def main():
#Get the data that was sent from the Web page
query = os.environ['QUERY_STRING']
#Get the number out of QUERY_STRING
key, val = query.split('=')
if key == 'data':
#We really should check that val contains a valid integer
#Save the current time and the received data to outfile
s = '%s, %s\n' % (time.ctime(), val)
with open(outfile, 'a+t') as f:
f.write(s)
#Send browser back to the refering Web page
href = os.environ['HTTP_REFERER']
s = 'Content-type: text/html' + CRLF * 2
s += '<meta http-equiv="REFRESH" content="0;url=%s">' % href
print s
if __name__ == '__main__':
main()
When you save this program to your hard drive, make sure that you give it execute permissions. Since you're using Flask, I assume your server is configured to run Python CGI programs and that you know what directory it looks in for such programs.
I hope this helps.

Sending data from javascript to python

I have a website which contains some JavaScript code. On a different server, I have a python script. I am trying to send data to the python script and then have the python script return some text.
The JavaScript calls the python file with a call like:
//server.example.com/cgi-bin/pythonscript.py?type=ball&color=blue
My first question is how do I read in those parameters (type=ball and color=blue) in the python script? Would using any of these methods work:
parameters=input()
or
parameters=sys.argv[1:]
or
import cgi
parameters=cgi.FieldStorage()
My second question is then how to I send data back to the JavaScript code. Now, I will be sending text back using JSONP (JavaScript uses callback). Will a simple print or return statement work as shown below?
output_text='callback_func('+json.dump(output_info)+');'
print(output_text)
or
return output_text
Thanks for the help!!! It is really appreciated!
If you're using the cgi module, then you use FieldStorage and print output
Taken from http://docs.python.org/2/library/cgi.html - this can be used as a base that you just tweak slightly...
import cgi
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
form = cgi.FieldStorage()
if "name" not in form or "addr" not in form:
print "<H1>Error</H1>"
print "Please fill in the name and addr fields."
return
print "<p>name:", form["name"].value
print "<p>addr:", form["addr"].value

Categories

Resources