in weppy how can i send data to python from javascript using ajax()

142 Views Asked by At

I am trying to send an id number to my weppy backend via ajax I have tried as many things as I can think of but am sure I just don't understand how to do it.

I have collected an id from my HTML page on click and would like to send it to the server script right now my ajax looks like

$(.testclick).click(function(e){
  var idnum = e.target.id;
  ajax("{{=url('post')}}", [], ':eval');
});

I have tried including the idnum variable in multiple places hoping to figure it out with no such luck

the post function looks like

@app.route()
def post(idnum):
  idnum = idnum
  print(idnum)
  return

right now I am just trying to make it work it doesn't actually do anything but print to the console atm

thanks in advance!

2

There are 2 best solutions below

0
On

In order to run python script from javascript you can use CGI. Here is the javascript code:

$(.testclick).click(function(e){
var reqobj;
reqobj = {idnum: e.target.id}

// AJAX
var response = $.ajax({
type: "POST",
url: "/script/sample.py",
data: reqobj

});
}

Python script (sample.py):

import cgi, cgitb
data= cgi.FieldStorage()

# Get data from fields
input = data["idnum"]

print(input)

To get both scripts working you need to have a web server and configure it to execute python script. Here's [a link] https://www.linux.com/blog/configuring-apache2-run-python-scripts

0
On

As from weppy docs:

ajax helper asynchronously calls the url, passes the values of the field inputs with the name equal to one of the names in the list, then stores the response in the innerHTML of the tag with its id equal to target. The third argument can also be the :eval string, which leads to the evaluation via JavaScript of the string returned by the server.

If you want to use an arbitrary value for an ajax request using that helper, you need to put it in the requested url, but before that, you need to accept an url variable on your route:

@app.route('/click/<str:element_id>')
def click(element_id):
    return 'alert("clicked on ' + element_id + '");'

Then on the html side:

$(".testclick").click(function(e){
    ajax("{{=url('click')}}/" + e.target.id, [], ':eval');
});

Note that the ajax helper provided by weppy is intended to be used to render content inside a component of your page or to generate javascript code to be evaluated.

If you need to send and get arbitrary data to your backend, consider using the jQuery ajax method and json data instead.