Run python file from JavaScript [duplicate] - javascript

What I want is run python script just click on the button in the html page and show the python code result on my page.
Because it's just a small project, so I don't want to be overkill learning Django or other web frames even though I know it will work.
I made some searches, ajax seems the right solution for me, but I don't know how to execute python code by ajax. I know I can get some string back via ajax using following code:
function loadXMLDoc()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
}
Thanks in advance for anyone who can help.

To extend #Liongold's comment, The full workflow goes like this:
Overview of how this happens
The javascript code for a button click gets executed. This code is running on the client from a browser.
The AJAX request gets sent over the internet just like an HTTP request, which is interpreted by a web application running on the computer that will run the Python code.
The python code creates a response, and formats it for sending back to the client.
The javascript reads the response as plain text, and decides what it means and how to use it. JSON is a very popular format for exchanging data via AJAX
What you need to do
Either:
Learn a server-side python framework. Flask is lightweight and will probably do what you want. The largest obstacle I've found here is dealing with Cross-origin (CORS) problems. Get started at http://flask.pocoo.org/docs/0.10/quickstart/
OR
See if you can port the python script INTO the browser. Does the code need to be run on a specific computer ( the server ) or could it theoretically be converted into javascript and run within the webpage. If the language difference is your only problem, have a look at http://www.skulpt.org/

I ran into a similar problem, and after searching for several hours, this is how i solved it. Assuming that the html file and the python file are the same folder.
<script>
function runScript() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
alert('Successful .... ' + request.responseText);
} else {
alert('Something went wrong, status was ' + request.status);
}
}
};
request.open('POST', 'test.py', true);
request.send(null);
return false;
};
document.getElementById('script-button').onclick = runScript;
</script>
This goes to your html file
-----------------------------
<button type="button" id="script-button">
add this line at the top of your python file
---------------------------------------------
test.py
------------
#!C:\Python34\python.exe -u
print("Testing 123")
add this directive to httpd.conf (Apache)
-----------------------------------------
# "C:/xampp/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "C:/xampp/<path to your project on the web server>">
AllowOverride All
Options Indexes FollowSymLinks Includes ExecCGI
AddHandler cgi-script .py .pyc
Order allow,deny
Allow from all
Require all granted
</Directory>

Related

JavaScript / Python interaction in Linux without a REST framework?

I'm working on some changes to a page that needs to retrieve information from some files under /proc so the page can display version information to the user. Currently, the page is generated entirely by the Python script, which allows me to just read the file and put everything in the page at creation time.
However, this led to the issue that the version numbers wouldn't update when a new version of the software was uploaded. I don't want to regenerate the page every time a new package is installed, so I made the main page static and want to instead just query the information from a Python script and return it to the page to populate the page when loaded.
The Python scripts are set up as CGI and have sudo access, so there's no issue with them retrieving those files. However, if I wanted to use something like AJAX to call the Python script, is there any way I could return the data without using a REST framework such as Flask or Django? The application needs to be lightweight and preferably not rely on a new framework.
Is there a way I can do this with vanilla JavaScript and Python?
Ok, so the solution was fairly simple, I just made a few syntactical errors that led to it not working the first few times I tried it.
So the request looked like this:
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if((this.readyState == 4) && (this.status == 200)) {
var response = JSON.parse(this.responseText);
// Do stuff with the JSON here...
}
};
xhr.open("GET", scriptURL, true);
xhr.send();
}
From there, the Python script simply needed to do something like this to return JSON data containing my version numbers:
import sys, cgi, json
result = {}
result['success'] = True
result['message'] = "The command completed successfully"
d = {}
... write version information to the 'd' map ...
result['data'] = d
sys.stdout.write("Content-Type: text/plain\n\n")
sys.stdout.write(json.dumps(result))
sys.stdout.write("\n")
sys.stdout.close()
The most persistent problem that took me forever to find was I forgot a closing quotation in my script tag, which caused the whole page to not load.

xml data is not showing in html page

I am just trying to fetch xml data and showing it in html page using jscript. According to this tutorial i have written a sample code which is
<script>
xmlDoc=loadXMLDoc("http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml");
x=xmlDoc.getElementsByTagName('city');
for(i=0;i<x.length;i++)
{
att=x.item(i).attributes.getNamedItem("name");
document.write(att.value + "<br>");
}
</script>
<script >
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
My output in html page should be 'London'. But its showing nothing. Or plz tell about my mistake.
I think you're running into the infamous "same-origin policy" problem
To summarize, in AJAX you can't load XML content from a remote server, application or website (meaning XML data cannot originate from any domain outside of your own domain.
There area number of ways around this problem such as the use of a server-side proxy, instead of XML use JSONp or the use of CORS to break the sandbox your client app is in when running that code (if both your user's browser and the server-stack you're requesting to supports it).
Ajax is asynchronous.
You need to read about http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
That will do the business when the reply is received

Get text from a link in javascript

I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.

Problem with making a simple JS XmlHttpRequest call

Edit: Maybe I made the question more complex than it should. My questions is this: How do you make API calls to a server from JS.
I have to create a very simple client that makes GET and POST calls to our server and parses the returned XML. I am writing this in JavaScript, problem is I don't know how to program in JS (started to look into this just this morning)!
As n initial test, I am trying to ping to the Twitter API, here's the function that gets called when user enters the URL http://api.twitter.com/1/users/lookup.xml and hits the submit button:
function doRequest() {
var req_url, req_type, body;
req_url = document.getElementById('server_url').value;
req_type = document.getElementById('request_type').value;
alert("Connecting to url: " + req_url + " with HTTP method: " + req_type);
req = new XMLHttpRequest();
req.open(req_type, req_url, false, "username", "passwd");// synchronous conn
req.onreadystatechange=function() {
if (req.readyState == 4) {
alert(req.status);
}
}
req.send(null);
}
When I run this on FF, I get a
Access to restricted URI denied" code: "1012
error on Firebug. Stuff I googled suggested that this was a FF-specific problem so I switched to Chrome. Over there, the second alert comes up, but displays 0 as HTTP status code, which I found weird.
Can anyone spot what the problem is? People say this stuff is easier to use with JQuery but learning that on top of JS syntax is a bit too much now.
For security reasons, you cannot use AJAX to request a file from a different domain.
Since your Javascript isn't running on http://api.twitter.com, it cannot request files from http://api.twitter.com.
Instead, you can write server-side code on your domain to send you the file.

How can I take common large chunks of oft-reused HTML source code?

A slew of pages I've written for one of my web projects share some 144 identical lines of code, reproduced in each file. If I update one of those lines, I have to go back through ALL of the pages that share the code and update for each page. Is there a straightforward way to include HTML from a separate file?
And for bonus points, since so many pages use this code, it would be nice not to have to reload it for each page. Is there an easy way to store it in the browser's cache or only load the "content" section of the pages while leaving the rest of the page static?
Fountains of Thanks for any wisdom on this.
Mike
To include HTML from a separate file, use SSI (Server-Side Includes). This requires SSI support to be installed on the server, however.
You would write something like this in your files:
<!--#include file="included.html" -->
and that would include the file included.html when the page is accessed.
To load only the content of each page, use the XMLHTTPRequest object from JavaScript:
function LoadContent(url)
{
if (typeof(XMLHttpRequest) == "undefined")
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
// fallback for browsers without XMLHttpRequest
window.location.href = "no-ajax.php?url="+escape(url);
return;
}
}
}
else
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", url, false); // this request will be synchronous (will pause the script)
xmlhttp.send();
if(xmlhttp.status > 399) // 1xx, 2xx and 3xx status codes are not errors
{
// put error handling here
}
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
If we're assuming that you're talking straight html pages, with no server code (asp.net, php, or server side include ability), then in order to do both the including and the caching, you're going to need to use an iframe.
Each of your pages that duplicate the 144 lines of content should replace it with an iframe like so:
<iframe src="pagewithcontent.html"></iframe>
pagewithcontent.html would obviously be where you move the content to. The browser will cache the page appropriately, so that each parent page will simply get the shared content without making another request.
There's an article here that goes into great depth about html includes, and some javascript methods of doing it. I would strongly recommend against the javascript methods.
My answer reflects the assumption that you can't do anything on the server side. However, by far the best solution is to do so if you can.

Categories