Thomas Thomas - 3 months ago 17
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.

Python

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


Html

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


Javascript

<script>
function myFunction()
</script>


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.

Thanks

Answer

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
          }
       }
   };

   xmlhttp.open("GET", "/log", true);
   xmlhttp.send();
}