2

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

3
  • Unfortunately this question is way too broad. Rather, let JavaScript call another route via ajax. Commented Aug 22, 2016 at 20:06
  • 1
    Database record deletion cannot normally be done by Javascript due to it being a client-side language. What you want done, needs to be done server-side with PHP, Python, Java etc. Since you're using Python, you want to somehow send a request onClick back to your Flask-Python script. Your best bet would be using Jquery/Javascript to send a request back to your python script and using the request module to 'grab' it. Treating it as a flag for deletion. Commented Aug 22, 2016 at 20:17
  • @Joseph Thank you for the information! I will look into that. Commented Aug 23, 2016 at 13:05

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.