I have a button and when I click it I want js to execute a .py command on the server side. How do I do this?
I have a button and when I click it I want js to execute a .py command on the server side. How do I do this?
You can do this with a AJAX
command through JavaScript
, however, your AJAX
call will be a request in HTTP
(WEB) for the Python
script, so your command needs listen on the door for such requests and respond back.
Below is an example using
jQuery
of how this call can be done:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Python - jQuery Example</title>
<script src="http://code.jquery.com/jquery-2.0.3.js"></script><script>$(function(){$.ajax({url:"http://localhost/cgi-bin/you-command.py",
type: "post",
datatype: "html",
data: { var1: "foo", var2: "foo" },
success: function(response){
$("#div").html(response);
console.log("OK");
}
});
});
</script>
</head>
<body>
<div id="div">EMPTY</div>
</body>
</html>
If your Python
script does not accept HTTP
requests you will need to add a layer that does this and execute your command as desired.
#EDIT
Just use the CGI library of Python
import cgi, cgitb
data = cgi.FieldStorage()
output = data["var1"] // É assim que você captura os parâmetros passados.
print(output)
For this you need a layer between the backend and the front end, something like the django templates, in which case you would have a button (which could be "controlled" by js or not) that would send an object HTTP for a function in the backend. I think with an example it gets easier. Let's just assume a submit button to "trigger" something on the backend.
template.html
{% block content %}
<div class="container">
<form method="POST" class="viewform">
{% csrf_token %}
<--! Implemente o form aqui -->
<button type="submit" name="_submit" class="btn btn-primary btn-lg">Cadastrar</button>
</form>
</div>
{% endblock %}
views.py
def teste1(request):
if request.method == 'POST':
# Submit pressionado
print ('Ok, botão pressionado)
else:
pass
return render(request, 'template.html' )
It's important to keep in mind that the idea of an element in the front end directly executing a command on the back end is a bad idea, so the need for the middle layer, in this example the button does not execute anything in the back end, it only sends a request to the back and it does what it needs, that is, the front nor does it "dream" if what is going to be executed in the back will be in python , c, or bash. This ensures that if there is a need to radically change the language / platform / environment on one side, there will be no side effects on the other.