I have a button in HTML:
<button id="save" type="button" onclick="save()">Save</button>
and in javascript I want it to run something in node.js, something that's not client side.
So something like this is what I am looking for:
function save() {
//run script from server
}
And if this script MUST be ran as if I was typing node script.js
The reason the script has to be ran as if I was typing it was because it's saving a file to the node.js server, a json to be exact, and that file must be on the node.js server for my application.
So you really can't execute a server-function from the client side, but you can maybe send a post-request and call the function on the server side, or you can use sockets to communicate with the server. Either way, it would be horrible security-wise, if you would be able to interact with the server on that way.
Related
I have a problem in calling my python function from my javascript file.
I'm using a simple server with python3 -m http.server, so no actual backend..my javascripts are in the front end.
I have a python file called write.py it has a function that I want to execute from my javascript file
write.py file:
def save_vit(text,name):
f = open(name + ".xml", "w+")
f.write(text)
f.close()
the javascript part that i have tried:(but didn't work)
$.ajax({
type: "POST",
url: "write.py",
data: { text: xmlDoc,name: name}});
xmlDoc is a string that has an xml document.
name is a variable that has the name of the file for the python function.
So my question is, what am I missing to call write.py from my js file or how to call it if this approach is wrong?
You are using http.server to serve the content of a folder, as files, not to execute them, so in the best case scenario, http.server will respond with the content of the write.py file instead of executing it.
You need to create a webserver that has a endpoint where the code of write.py is integrated.
You can't send a POST http request to run a python script.
You need to have the python script running on a server, that is able to take restful API calls, to run the script and return a value.
For example, you can run a small flask app that takes in your POST route, which runs a script and returns the value of the script back to the client that accessed the POST route.
Python is running on the server side ... JavaScript is running on the client side.
So, the only way for JavaScript to ask for a Python routine to be run is through an asynchronous AJAX request which you will have to build.
I am on a dreamhost server and have some HTML that calls some javascript when a button is pressed. I am trying to call a python script when this button is tapped.
First off, to my knowledge as I am on a shared host I cannot use AJAX as it is not supported, so I need to do this without AJAX. Right now I am trying to do a XMLHttpRequest which is working.
I also realize doing an XMLHttpRequest is not the best way since the files are both on the server there must be a way to just call the file directly?
So if someone call tell me how to call it directly or help me fix this error in the browser console that would be great.
Thanks for the help
EDIT
I have an HTML file when a user taps a button on this file it calls some javascript that is in the HTML file. This javascript currently makes a POST Request, to a python script that is on the same server and the HTML file.
What I want instead of making a post request to the python file that is on the server, I want to just directly call the python file, from the javascript that runs, when the button the clicked in the HTML file.
Both the HTML file which contains the javascript and the python file are on the same server. And I don't want the python to run in the browser, I want it to run in the background on the server.
How can I use the Javascript to call this python file?
As far as I understand your question what you are looking to do is called a "remote procedure call", or some sort of Service Oriented Architecture (SOA).
You are on a right track in making a POST request to the server.
You can setup a middleware like flask, or cherrypy to run the script when you send a GET, PUT, POST ... request. And inside of the middleware controller you can call your script.
Basically you have started to create a RESTful api, and its a pretty standard way these days to run logic on the backend.
Some examples of different frameworks for doing url routing:
Python:
CherryPy: http://docs.cherrypy.org/en/latest/tutorials.html#tutorial-9-data-is-all-my-life
Flask: http://flask.pocoo.org/docs/0.10/quickstart/
a longer list of lower level python: http://wsgi.readthedocs.org/en/latest/libraries.html
NodeJs:
Express: http://expressjs.com/guide/routing.html
Koa: https://github.com/koajs/route
Hapi: http://hapijs.com/tutorials/routing
Also very good is this question: JSON, REST, SOAP, WSDL, and SOA: How do they all link together
Another way that you could do this from the browser would be to use sockets, which opens a connection between the client and the server.
Inside the javscript you could use socketio:
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.connect('http://localhost:8000')
socket.emit('run_a_script_event', {arg1: 'hello', arg2: 'world'});
</script>
And in your python code you could use the socketio client for python (https://pypi.python.org/pypi/socketIO-client):
from your_module import thescript
from socketIO_client import SocketIO, LoggingNamespace
def run_a_script(*args):
print('arg1 and arg2', args)
thescript()
socketIO = SocketIO('localhost', 8000, LoggingNamespace)
socketIO.on('run_a_script_event', run_a_script)
Looks like there is also a version specifically for flask: https://flask-socketio.readthedocs.org/en/latest/
Or you could run the python directly in the browser by converting it to javascript with a transpiler:
http://www.skulpt.org/
Or you could use node javascript to spawn a child process which runs the python script:
https://stackoverflow.com/a/20973067/2026508
Or you can import the python script into node like:
Use of node-python to execute python scripts from web application hosted under python?
What I'm trying to do is what can be done in a browser by running this javascript: document.getElementById('foo').bar().
I don't know how to go about doing this in python. I used to do stuff with submitting forms using twill and sending responses with urllib2, but I never had to do any javascript. Where should I start?
I guess you are building up your html/js code in the server side and when requested, you will serve that code to the client? As client code will be served you can add it to you logic in the server side:
getFooElement = 1;
if getFooElement:
print "document.getElementById('foo').bar()"
else
print "HTML/JS code"
I've written a PHP script that reads data from Facebook user's profile and sends it to my server through AJAX. This script needs to run in intervals, so I added a cron. All the PHP functions and interactions with databases through MySQL are working with cron. But AJAX is not. I know it's (JavaScript) a client-side script, but is there any other way? How I can execute JavaScript (AJAX) written in a file through cron.
Ajax is a client-side technology you cannot run that in PHP console.
Ajax calls consist of an API (application programming interface). The API is the system of calls through which a client (the browser) communicates with a server (the server).
In your case, the client is the computer on which the PHP script is running and the server is your server. If you can replicate the API used in JavaScript in PHP then you are away on hack.
For example, suppose the sever you were communicating with had a service called "postupdate.php" and it took one value called "update", the API call might look like this in JavaScript:
<script type="text/javascript">
var response;
$.ajax({
url: "http://www.example.com/postupdate.php?update=This_is_my_update"
}).success(function(text) {
response = text;
});
</script>
The same API call might look like this in PHP:
<?php
$response = file_get_contents("http://www.example.com/postupdate.php?update=This_is_my_update")
?>
This example assumes the API uses the HTTP GET method. APIs that use HTTP POST methods are more complicated but can be used in PHP as well.
Did not have luck with these examples:
Javascript File remove
Javascript FSO DeleteFile Method
Deleting a File
There are no special permissions on the file.
Is there a way to do this in JQuery?
The requirement is - a certain file must be deleted from the web directory when another page is loaded. There is no security issue as this is on a closed network.
Any help is appreciated.
Thanks.
With pure JavaScript, it can't be done. Using an AJAX call to a server side script that deletes the file would work though.
Javascript cannot delete files, it is prevented as it would lead to HUGE security vulnerabilities. THose links are for ActiveX controls that are handled through JS. Use a server side language.
You can't delete files over HTTP (well in theory you can, but it's not implemented.)
The easiest way is to set up a tiny server side script (e.g. in ASP or PHP) and to call that from JavaScript. The server side script needs the proper permissions to do the deletion, but otherwise there is no problem.
In PHP the start would look like this: (Not expanding solution to a fully secure one because you're not saying what platform you are on)
<?
// STILL INSECURE!!!!
// Do not use in any public place without authentication.
// Allows deletion of any file within /my/files
// Usage: filename.php?file=filename
$basedir = "/my/files";
$file_to_delete = $_REQUEST["file"];
$path = realpath($basedir."/".$file_to_delete);
if (substr($path, 0, strlen($basedir)) != $basedir)
die ("Access denied");
unlink($path);
?>
you would call the script like this:
http://yourserver/directory/delete_file.php?file=directory/filename
You cannot delete a file on a remote server using only JavaScript running in a visitor's browser. This must be done with a server-side script.
If you are doing this in a RESTFUL way, you would send an HTTP DELETE request.
jQuery's ajax method states that you can use the method parameter to specify 'DELETE' but notes that some browsers may not support it.
Obviously you will need a webserver which will accept a DELETE request, and apply some sort of authentication/authorization so that joe random visitor can't delete your files. I believe Apache's mod_dav will get you started here.
Javascript is a client side language. So you are not able to delete file on server directly. All examples that you provide may be used only for deleting files on your local machine but not into server.
But you may call some server page function that will delete file.
You can't delete files with JavaScript as it is run locally. So, it doesn't even touch external files.
You need to use a server side language that has access to editing the files such as PHP, RoR, or ASP.
You can however use jQuery to call the server side code via AJAX such as $.get or $.post and then the server side code deletes it and it would seem as though JS is deleting the files.