I have a python script which I want to execute when someone clicks on a button in an HTML/PHP web page in the browser. How can this be achieved and what is the best way of doing it?
You need to use flask server for this requirement as browser can not access local file.
By using flask, You need to write Ajax call in .js
.
Sample Ajax call.
$(document).ready(function () {
$('#<ButtonID>').click(function (event) {
$.ajax({
url: '/<Flask URL>',
type: 'POST',
success: function (data) {
<DATA OBJECT>
},
});
event.preventDefault();
});
});
Sample Flask function
@app.route('/<Flask URL>',methods=['POST'])
def result():
try:
<DO>
except:
logger.error()
raise
return jsonify({'data':<Python variable>})
You might need to import necessary modules.