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");
    }
    xmlhttp.open("GET","/servlet/Welcome.do?firstName=Devesh&lastName=Sharma",true);
    xmlhttp.send();

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:

request.getParameter("firstName")
request.getParameter("lastName")
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s