0

I have a system where people can add roles and remove roles from a list (This is what it looks like: https://s7.gifyu.com/images/idea9b50431c2edc0295.gif ) but want a way to save that data when the user clicks "Save". I was thinking I could use JS to get the contents of the ul and run a python function to save the data, but I can figure out how to do it. I've tried Passing data from javascript into Flask and Python Flask calling functions using buttons but couldn't get it working. The problem with the second one is that I couldn't pass data into the function.

This is the code for the ul:

<ul class="role_box_roles" id="rbroles">
    {% for role in modroles %}
    <li class="role_box_role" style="border-color: rgb(255, 255, 255);">
        <button class="role_remove_button" onclick="remove_option('{{role}}', this)" type="button" style="background-color: rgb(255, 255, 255);">-</button>
        <span>{{role}}</span>
                        </li>
    {% endfor %}
    <li id="plusbutton"><button class="role_add" type="button" onclick="show_options()">+</button></li>
</ul>

I am trying to save the role names ({{role}}).

The save button is below the ul

<div id="save_changes_button" class="save_changes_button" onclick="">Save</div>

I'm trying to save it in a dict stored in the flask file (the python file that is running flask/the website)

I can give extra information if it's required.

User-92
  • 374
  • 3
  • 13

2 Answers2

1

Save Button Create Ids for tags ( and )

<span id="myspan">{{role}}</span>
<a id="save_changes_button" class="save_changes_button">Save</a>

JS Listen for click on save_changes_button, once this happens

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"</script>
<script>
$(document).ready(function() {
    $('#save_changes_button').click(function (event) {
    event.preventDefault();
    $('#save_changes_button').prop("disabled", true);
    $.ajax({
         data : { my_role : $('#myspan').text() }, //grab text between span tags
         type : 'POST',
         url : '/saverole', //post grabbed text to flask endpoint for saving role
         success: function (data) { console.log('Sent Successfully') },
         error: function (e) { console.log('Submission failed...') }
    });
});
})
</script>

FLASK

@app.route('/saverole', methods=['POST', 'GET'])
def saverole():
    s_role = request.form['my_role'] #parse received content to varaible
    role_dict = {'role': s_role} #construct a dictionary with variable 
    return ('', 205) #or whatever you wish to return
Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18
-1

the only way to send data from a webpage js back to your server is via a ajax POST/GET method from your js

by defining a route which accepts the data in flask and a js ajax call to POST that data to that flask route onClick (or any other user changes on webpage, handled by js)