How do you execute a server-side Python script using jQuery? - javascript

I have a very simple Python file, called python1.py, whose contents are:
f = open('C:\\Temp\\test.txt', 'w')
f.write('Succeeded')
f.close()
I wish to execute this from JavaScript, like so:
jQuery.ajax({
type: "POST",
url: "/cgi-bin/python1.py",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
However, all that happens is that I get an alert showing me the contents of the Python script. The file C:\Temp\test.txt does not get created, so clearly the Python was not executed.
How do I persuade the code to execute the Python script instead of just reading it?

You simply need to configure your web server to execute your *.py scripts, instead of serving them as plain text.
If you are using Apache as a web server, you need to enable mod_python or mod_wsgi.
EDIT:
Since you are using using Apache, you may want to check the following article, which briefly describes how to set up the mod_python module:
A Brief Introduction to Apache's mod_python Module

You could also use the opensource project Pico. It's a really elegant way of calling server side Python code from client side Javascript.
The author has provided some simple examples here https://github.com/fergalwalsh/pico/wiki/Example-1:-Hello-World

Are you able to execute the script directly from the browser. This looks more like a webserver config issue than jquery's

If your script is that simple, you would be best off using CGI on the server side rather than mod_python or mod_wsgi as suggested by others. For details on how to set up Apache for CGI with Python and simple script examples see:
http://webpython.codepoint.net/cgi_tutorial

Related

What is server-side scripting ajax

Hi I'm new to programming and making a project exactly like these Real time GPS Tracker on JUST HTML / JS and Google Maps to be run on a handphone
My Next step is all users should see others location and one of the answers said
you'd have to send the points to a server-side script using AJAX.
I know how ajax works i just don't know what he meant by server-side script
$.ajax({
url: "sample.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
My Questions is:
Is the code above consider a server-side script? if no any examples
Should i make new .php file?
You have a file that exist in you server so one cannot access it using their browesers.In your case that test.html file is residing in server. it can be .php file .js file ....
The code above is not a server side scripting language as the url is still point to a .html page.
A server side scripting language is a language that runs on the server rather than on the client. example of a server side scripting language is php.

Call Python scripts thanks to JS or HTML

Is there any way or tips to call a Python file (or functions) winthin a .js file (called on a HTML web page).
Indeed, I did the following tip :
- configure my server (it's Apache) to run Python files (CGI)
- created a Python file on the following structure :
print("<head>....</head>")
print("<body>....</body>")
But what I want is to call a Python file (a real one, with classes, functions or other things) on the Javascript. Any ways to do it ?
(something with Ajax or other stuffs)
Thanks, Clément
EDIT
Here's what I want to achieve :
my structure :
1) HTML/CSS/JS files to create an interactive chat
2) a Python file to process the answers on the chat
My goal
On each post on the chat, a Javascript function of my .js file is called. This function need to run my Python file, and my Python file is supposed to return something. The Python file is a pure Python file, no HTML or other things.
What I've done
I created a server thanks to XAMPP. Moreover and as I said before, I tried the thing with print("...") on each line, but it's by far not what I want.
EDIT 2
I already tried a thing with AJAX like :
$(".mytext").on("keyup", function(e){
if (e.which == 13){
var text = $(this).val();
if (text !== ""){
insertChat("you", text);
$(this).val('');
$.ajax({
type: "POST",
url: "test.py"
});
}
}
});
but I get an error :
The error I get is on the HTML console, in French :
Erreur d’analyse XML : mal formé
Emplacement : http://localhost/test/test.py
Numéro de ligne 1, Colonne 2
so in English:
Error of XML analysis : malformed
Path : http://localhost/test/test.py
Line 1, column 2
JavaScript runs in your browser. Python cannot run in your browser.
The Javascript code can create requests to a server. On the server you can run all kinds of code, including python. The python script(s) have to reside on the server and the server has to be configured accordingly (see WSGI, CGI, "How to use python on the web").
Edit:
Answer to updated question:
What you want is to create XmlHttpRequests from JavaScript to the python chat program running on the server. The data format will be JSON (not XML). This technique is called AJAX ("Asynchronous javascript and XML"). I suggest you read some tutorials on these topics. The web framework for Python is called Django.

File path issue using Node.js

I'm deploying a node.js based application to IBM's Bluemix and have added a few features to one of the samples they provide. I've added an additional javascript file that makes an ajax call to PHP, but the PHP file is coming back as not found because my path is incorrect. I've tried putting the file everywhere and it's just not being found. I'm thinking (as a total node noobie) that I'm missing some mysterious configuration or something.
In the main directory (among other things), the structure is like this:
-- views
- index.ejs (this is the main displayed code)
-- public
- js
- custom.js (my added file)
- all the other necessary js files
- css
- img
- php - I added this directory
- get-twitter.php - I added this...custom.js makes an ajax call here
In custom.js, I have this:
$("#get-twitter").click(function(event) {
handle = $('#twitter-handle').val();
$.ajax({
url: 'php/get-twitter.php',
type: 'POST',
dataType: 'JSON',
data: {
handle: handle,
},
success: function(data) {
console.log(data);
$.each(data, function(index, val) {
console.log(val.text);
});
}
});
});
When I try to make this call, the file isn't found, but the path is this: https://myapp.mybluemix.net/php/get-twitter.php It should be in views/php/get-twitter.php, but I'm guessing this is a configuration issue on my end.
I've tried every iteration of this: url: 'php/get-twitter.php', and put the PHP file in every directory and nothing is working.
What am I missing here?
There is no way to run PHP scripts from node. You will need to set up a server that supports PHP, and make your requests there. One option would be Apache.
Realistically, you probably don't want to set up an entire server for the purpose of running a single PHP script. A more reasonable solution would be to port the PHP script to run on Node. There are many packages for twitter API integration on NPM (e.g. the twitter module).
If the server has PHP installed, then you can try to use exec to run the PHP file using the command line interpreter and get the output. Obviously you need to refactor your code to work with arguments passed by shell ($args) and display a JSON response that will be catched by node. For example:
exec('php -f /project/file.php', function (err, out) {
if (!err) {
const output = JSON.parse(out);
// do something with the object
}
});
As #positlabs said, keep the things simpler and port the script to JavaScript.

Generate some xml in javascript, prompt user to save it

I'd like to make an XML document in JavaScript then have a save dialog appear.
It's OK if they have to click before the save can occur.
It's *not* OK if I *have* to use IE to achieve this (I don't even need to support it at all). However, Windows is a required platform (so Firefox or Chrome are the preferred browsers if I can only do this in one browser).
It's *not* OK if I need a web server. But conversely, I don't want to require the JavaScript to be run on a local file only, i.e. elevated privileges -- if possible. That is, I'd like to to run locally or on a *static* host. But just locally is OK.
It's OK to have to bend over backwards to do this. The file won't be very big, but internet access might either be there, be spotty or just not be a possibility at all -- see (3).
So far the only ideas I have seen are to save the XML to an iframe and save that document -- but it seems that you can only do this in IE? Also, that I could construct a data URI and place that in a link. My fear here is that it will just open the XML file in the window, rather than prompt the user to save it.
I know that if I require the JavaScript to be local, I can raise privileges and just directly save the file (or hopefully cause a save dialog box to appear). However, I'd much prefer a solution where I do not require raised privileges (even a Firefox 3.6 only solution).
I apologize if this offends anyone's sensibilities (for example, not supporting every browser). I basically want to write an offline application and Javascript/HTML/CSS seem to be the best candidate considering the complexity of the requirements and the time available. However, I have this single requirement of being able to save data that must be overcome before I can choose this line of development.
How about this downloadify script?
Which is based on Flash and jQuery, which can prompt you dialog box to save file in your computer.
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){
alert('Your File Has Been Saved!');
},
onCancel: function(){
alert('You have cancelled the saving of this file.');
},
onError: function(){
alert('You must put something in the File Contents or there will be nothing to save!');
},
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
Using a base64 encoded data URI, this is possible with only html & js. What you can do is encode the data that you want to save (in your case, a string of XML data) into base64, using a js library like jquery-base64 by carlo. Then put the encoded string into a link, and add your link to the DOM.
Example using the library I mentioned (as well as jquery):
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
//include jquery and jquery-base64 here (or whatever library you want to use)
document.write('click to make save dialog');
</script>
</body>
</html>
...and remember to make the content-type something like application/octet-stream so the browser doesn't try to open it.
Warning: some older IE versions don't support base64, but you said that didn't matter, so this should work fine for you.
Without any more insight into your specific requirements, I would not recommend a pure Javascript/HTML solution. From a user perspective you would probably get the best results writing a native application. However if it will be faster to use Javascript/HTML, I recommend using a local application hosting a lightweight web server to serve up your content. That way you can cleanly handle the file saving server-side while focusing the bulk of your effort on the front-end application.
You can code up a web server in - for example - Python or Ruby using very few lines of code and without 3rd party libraries. For example, see:
Making a simple web server in python
WEBrick - Writing a custom servlet
python-trick-really-little-http-server - This one is really simple, and will easily let you server up all of your HTML/CSS/JS files:
"""
Serves files out of its current directory.
Doesn't handle POST requests.
"""
import SocketServer
import SimpleHTTPServer
PORT = 8080
def move():
""" sample function to be called via a URL"""
return 'hi'
class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
#Sample values in self for URL: http://localhost:8080/jsxmlrpc-0.3/
#self.path '/jsxmlrpc-0.3/'
#self.raw_requestline 'GET /jsxmlrpc-0.3/ HTTP/1.1rn'
#self.client_address ('127.0.0.1', 3727)
if self.path=='/move':
#This URL will trigger our sample function and send what it returns back to the browser
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(move()) #call sample function here
return
else:
#serve files, and directory listings by following self.path from
#current working directory
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
httpd = SocketServer.ThreadingTCPServer(('localhost', PORT),CustomHandler)
print "serving at port", PORT
httpd.serve_forever()
Finally - Depending on who will be using your application, you also have the option of compiling a Python program into a Frozen Binary so the end user does not have to have Python installed on their machine.
Javascript is not allowed to write to a local machine. Your question is similar to this one.
I suggest creating a simple desktop app.
Is localhost PHP server ok? Web traditionally can't save to hard drive because of security concerns. PHP can push files though it requires a server.
Print to PDF plugins are available for available for all browsers. Install once, print to PDF forever. Then, you can use a javascript or Flash to call a Print function.
Also, if you are developing for an environment where internet access is spotty, conwider using VB.NET or some other desktop language.
EDIT:
You can use the browser's Print function.
Are you looking for something like this?
If PHP is ok, if would be much easier.
With IE you could use document.execCommand, but I note that IE is not an option.
Here's something that looks like it might help, although it will not prompt with SaveAs dialog, https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FOL.
One simple but odd way to do this that doesn't require any Flash is to create an <a/> with a data URI for its href. This even has pretty good cross-browser support, although for IE it must be at least version 8 and the URI must be < 32k. It looks like someone else on SO has more to say on the topic.
Why not use a hybrid flash for client and some server solution server-side. Most people have flash so you can default to client side to conserve resources on the server.

jquery.get returning php code?

I am trying to use jquery's ajax $.get(...) function to send a request to my server and have it return some data. I am using the following code:
$.get("php/getRocks.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Instead of getting the the data back, it just returns the entire php file as a string. Am I doing something wrong? Thanks for the help.
Is PHP installed on your server? This is a server issue. For some reason your .php file isn't being handled properly and it is returning the PHP code in plain text.
This is in response to:
Well, I seem to have solved the
problem, sort of. Apparently, if I
access the site localy, php doesn't
work, but if I use the domain name, it
does. Anyone know why? Or better yet,
a way to fix this?
Thanks to everyone for the help!
When working locally (and it always is a good idea to do so before uploading to a live environment) you need to setup PHP on your computer so that it can run the pages you require. A browser will not do it for you as it is a server side technology. You can download a package like Uniform Server, that will give you a full server environment for you to work with.
I have the same problem (using MAMP on mac), and while I haven't solved it, I am a step closer.
Basically, it would appear to have something to do with subdirectories/document root. If I set my url as getRocks.php (and move my script there), it works (I get content back), but if I get it as php/getRocks.php, it does not work (I get the php code back).
Perhaps MAMP is doing something add with response types within subdirectories? Am going to take a further look, but hopefully this helps lead you in the right direction.
Well, I seem to have solved the problem, sort of. Apparently, if I access the site localy, php doesn't work, but if I use the domain name, it does. Anyone know why? Or better yet, a way to fix this?
Thanks to everyone for the help!
1st. make sure you have php installed
If you are using linux / apache2 and php 5
u need to compile/install apache and load php via dso
eg:
LoadModule php5_module modules/libphp5.so
In my humble opinion it has got nothing todo with your jQuery but your web server installation/config:
If it is apache make sure you add this line in your conf file:
AddType application/x-httpd-php .php
More reading about php and apache if you are using php anad apache in linux/nix eg: http://dan.drydog.com/apache2php.html

Categories