Sending data from javascript to python - javascript

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

Related

When a servlet output java script (page show one string), how to use "curl " (or java code) to visit this servlet to get same result?

I am a java newbie and met this question, anyone can help would be appreciate ;)
Actually, I write a java servlet, and this servlet, just output javascript code to generate a virtual html page, and in this html's JS code will output a 'String' I need (acutally decrypted RSA psd). this works fine when use browser, but when I used 'curl' command (java code also) to visit this servlet, it returns just the whole JS code ,not the 'String' I needed.
I tried set "contentType text/html", "application/json" etc, but always return JS code. Is the method wrong? how can I get the String at backend?
some code like this:
out.println("<html>");
out.println("<script type=\"text/javascript\" src=\"./js/jsencrypt.js\"></script> ");
out.println("<head>");
out.println("</head>");
out.println("<body onload=testenc()>");
out.println("</body>");
out.println("<script>");
out.println(" function testenc() ");
out.println("{");
out.println(" var encrypts = new JSEncrypt();");
out.println("encrypts.setPublicKey('MIGfMA0GCSqG.....
The browser just display like:
MGFuXPaCe+NgHUYQh8Xq86ooG13RJaxwyX2ZxIxhm+ewi/rrQPKbnz0hugwxdWcy3wBLuTx5bxougDLU0Bo...
But curl command will return whole source code?
any help would be thanks.

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.

How to update JavaScript variable using PHP

I have a JavaScript file named a pricing.js which contains this content in it:
var price_arr = new Array('$ 16.95','$ 30.95','$ 49.95','$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95');
But I want to to update this part of JavaScript file using PHP so please help me in this how can I update this part of the content from JavaScript file using PHP?
'$ 16.95','$ 30.95','$ 49.95','$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95'
Please understand that Javascript is Client Side code and PHP is server side code.
There can be 2 possible ways or scenarios which you want to achieve:
If you want to manipulate the JS file before sending it to client, you can rename the Javascript file to have .php extension and write php code to provide a variable. For Ex:
<?php
// write php code to create a string of values using a for loop
$price_array_string = "'$ 16.95','$ 30.95','$ 49.95',
'$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95'";
// Javscript Code var price_arr = new Array(`<?`php echo $price_array_string ?>);
The other alternative is that you get the value of price array by making an Ajax Request to a PHP web service.
Simply give the pricing.js file a .php extension. You can then include PHP in the javascript file the way you would for any other page. Just be sure your HTML code specifies that it's still "text/javascript" when you load it. You'll probably want to set the content-type in the PHP file as well, like so: header("Content-type: text/javascript");
Using your PHP script you can put a value in an HTML5 data attribute of an element on your page and then read it from your JavaScript, e.g. <body data-array="'$ 16.95','$ 30.95'"> can be generated with PHP, and then read with JS: var are = new Array($('body').attr('data-array').split(',')). Here jQuery is used in order to read the attribute value, but you can also do it with pure JavaScript.

Passing form data to python

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

Python and reading JavaScript variable value

I am very new to Python programming, so please bear with me.
I have an HTML file with several div layers. This file is opened in a webkit.WebView object. Each div layer saves a value in a global variable (JavaScript) when clicked upon.
How can I read the value of that global JavaScript variable from my Python script?
I found some answers but they don't seem to fit my situation (but I can be wrong, of course):
Passing JavaScript variable to Python
Parse JavaScript variable with Python
[EDIT]
I'm using webkit.WebView because I have to show this in an existing glade (libglade) application.
try this out. It uses the addToJavaScriptWindowObject method to add a QObject into the QWebView. This will enable communication between your python script and the HMTL/Javascript in your webview. The example below will let you change the value of the javascript global variable message to whatever value you want through a JavaScript prompt, then whenever you click on the Python Print Message link it will execute your python code that will take the javascript value and just print it to the console.
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
HTML = """
<html><body onload="broker.print_msg(message)">
<script>var message = 'print_msg message'</script>
Change Message<br/>
Python Print Message
</body></html>
"""
class Broker(QtCore.QObject):
#QtCore.pyqtSlot(str)
def print_msg(self, data):
print data
app = QtGui.QApplication(sys.argv)
view = QtWebKit.QWebView()
view.page().mainFrame().addToJavaScriptWindowObject('broker', Broker(view))
view.setHtml(HTML)
window = QtGui.QMainWindow()
window.setCentralWidget(view)
window.show()
sys.exit(app.exec_())
I know this is old question, but still answering it with the hope that it will be useful to someone.
You can use alert handler and read the value in python side. http://webkitgtk.org/reference/webkitgtk/stable/webkitgtk-webkitwebview.html#WebKitWebView-script-alert
Example on button click you can have action that says
alert("Button Clicked");
On python side you will get the alert notification and you can parse the string. If the object is not a simple object, you will have to convert it to string format that can be parsed on python side. I have seen few examples of alert handler. https://github.com/nhrdl/notesMD/blob/master/notesmd.py is one that I wrote and uses alert handlers to pass lot of data between javascript and python

Categories

Resources