Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call python function from JS

Tags:

I am trying to call a function in Python from my JavaScript code. I used the code explained here but it does not work for me.

Here is my JS code:

<!DOCTYPE html> <body> <script type="text/javascript" src="d3/d3.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>   <script> text ="xx";  $.ajax({ type: "POST", url: "~/reverse_pca.py", data: { param: text} }).done(function(o) {     console.log(data);     console.log(text); }); 

Python Code:

import csv from numpy import genfromtxt from numpy import matrix  def main():     ...     return x  if __name__ == "__main__":     x=main()     return x; 

Do you know what is wrong with it?

like image 946
Bahador Saket Avatar asked Aug 29 '15 17:08

Bahador Saket


People also ask

Can I call Python function in JavaScript?

You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript $. ajax({ type: "POST", url: "~/pythoncode.py", data: { param: text} }). done(function( o ) { // do something }); There are a variety of approaches that can be taken to solve the same problem Call Python Function From Javascript.

Can I use Python and JavaScript together?

It can be used for developing desktop as well as web applications. Q #5) Can I learn JavaScript and Python at the same time? Answer: Yes, Javascript and Python can both be learned at the same time. Javascript is mainly used for front-end programming whereas Python is used for backend programming.

How do I run a Python script from node JS?

Easiest way I know of is to use "child_process" package which comes packaged with node. Then you can do something like: const spawn = require("child_process"). spawn; const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);


2 Answers

Apart from the mentioned points and assuming you already have a proper setup to serve your python script and return the response. You should submit an asynchronous request, especially if the python code does some heavy computation.

function postData(input) {     $.ajax({         type: "POST",         url: "/reverse_pca.py",         data: { param: input },         success: callbackFunc     }); }  function callbackFunc(response) {     // do something with the response     console.log(response); }  postData('data to process'); 

If you only do some light computation and you have no problem working with a code deprecated as of jQuery 1.8, go with the synchronous approach. This is not recommended as it blocks the main thread.

function runPyScript(input){     var jqXHR = $.ajax({         type: "POST",         url: "/reverse_pca.py",         async: false,         data: { param: input }     });      return jqXHR.responseText; }  // do something with the response response= runPyScript('data to process'); console.log(response); 

Read more about it here: How do I return the response from an asynchronous call? and http://api.jquery.com/jquery.ajax/

like image 80
Farshid T Avatar answered Sep 22 '22 16:09

Farshid T


After searching for few hours, I ended up having the following, and it worked well. Hope this helps someone else in future.

HTML and JS code: loging.html:

<html>  <head>     <title>Flask Intro - login page</title>     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <link href="static/bootstrap.min.css" rel="stylesheet" media="screen">     <script type="text/javascript" src="http://code.jquery.com/jquery 2.1.4.min.js"></script>    </head>  <body>     <input id="submitbutton" type="submit" value="Test Send Data">     <!----------------------------------->     <script type="text/javascript">      function runPyScript(input){         var jqXHR = $.ajax({             type: "POST",             url: "/login",             async: false,             data: { mydata: input }         });          return jqXHR.responseText;     }      $('#submitbutton').click(function(){         datatosend = 'this is my matrix';         result = runPyScript(datatosend);         console.log('Got back ' + result);     });  </script> 

Python code: app.py:

from flask import Flask, render_template, redirect, url_for,request from flask import make_response app = Flask(__name__)  @app.route("/") def home():     return "hi" @app.route("/index")  @app.route('/login', methods=['GET', 'POST']) def login():    message = None    if request.method == 'POST':         datafromjs = request.form['mydata']         result = "return this"         resp = make_response('{"response": '+result+'}')         resp.headers['Content-Type'] = "application/json"         return resp         return render_template('login.html', message='')  if __name__ == "__main__":     app.run(debug = True) 

like image 23
Bahador Saket Avatar answered Sep 22 '22 16:09

Bahador Saket