JavaScript, Python

How to call Python function from JavaScript?

Well, there ain’t any special mechanism to do it really. In order to make this happen, all you need to understand is client server mechanism. JavaScript is client side, whereas Python is server side. That is, JavaScript is executed on client’s browser, and Python is executed on the server. Therefore, JavaScript cannot call Python function directly. All JavaScript can do is issue HTTP requests to server, and then server can handle those HTTP requests.

The following code snippet sends HTTP request to server:

 var xmlhttp;
    if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari support XMLHttpRequest object
        xmlhttp = new XMLHttpRequest();
    } else {
        // IE6, IE5 doesn't support XMLHttpRequest object
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

Now, on the server side you need to handle this request. That is, in Python file you need to catch these information being sent so that you can use it to call appropriate function. This is how to grab the sent parameters in Python file: