Thomas Thomas - 1 month ago 6x
HTML Question

How to trigger a variable/method in python from a html file with javascript

I want to have a hyperlink on a html page run a variable that is defined in my python file. The variable is going to clear my database. Here is the code I am trying to use.


def log():
cleardb = db.session.delete()
return render_template('log.html', cleardb=cleardb)


<a onclick="myFunction()">Clear database</a>


function myFunction()

I don't know what javascript I need to run the variable. I want to make the cleardb get triggered so that it will delete the database.



You need to make an ajax request with javascript to /log, it would look something like this:

function myFunction() {
  var xmlhttp = new XMLHttpRequest();

   xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
          if (xmlhttp.status == 200) {
              //Do Success functionality here
          else if (xmlhttp.status == 400) {
            //Handle 400 errors here
          else {
            //All other errors go here
   };"GET", "/log", true);