简体   繁体   中英

Removing a table row from a db on a button click

I have a table:

<table class="table" id="mytable">
  <tr>
    <td>Column 1</td>
    <td>Column 2</td>
    <td><button type="submit" class="btn removeButton">Remove</button></td>
  </tr>
</table>

On the 'removeButton' click I want to remove a given table row (they are going to be dynamically created afterwards). I want to send the data from this particular row with ajax so I can also remove it from a database. I managed to implement the row removal from the website, but I'm straggling with sending appropriate request and retrieving data from the request to remove it from the database.

My javascript code:

$(document).ready(function() {
$('#mytable').on('click', '.removeButton', function(events){
    var data_array = $('td').map(function(){
        return $(this).serializeArray();
    });
    $(this).closest('tr').remove();
    $.ajax({
        type: "DELETE",
        data: data_array,
        success:function(result){
            window.location.href = $SCRIPT_ROOT + '/main';
        }
    });
  });
});

Server side code:

@app.route('/main', methods=['GET', 'POST', 'DELETE'])
def main():
  if request.method == 'POST':
    insert_in_db(request.form)
    return redirect(url_for('next_page'))

  elif request.method == 'DELETE':
    #Retrieve data from the request and remove it from the database

  return render_template('next_page.html')

How can I send the data from the current table row (the one next to which the button has been clicked) in an ajax request and how can I retrieve it on the server side afterwards? I tried calling request.data but I get only an empty string. I tried request.form in the DELETE request and this gives me ImmutableMultiDict([]). Any tips? I'm currently using Flask as the web framework. Thanks!

To send the row data via the AJAX call -

$('#mytable').on('click', '.removeButton', function(events){
    var col1 = $(this).closest('tr').find('td').eq(0).html(); // or you could loop through the cells
    var col2 = $(this).closest('tr').find('td').eq(1).html();
    $(this).closest('tr').remove();
    $.ajax({
        type: "DELETE",
        data: {column1 : col1, column2 : col2}, // post values
        success:function(result){
            window.location.href = $SCRIPT_ROOT + '/main';
        }
    });
  });

These should be available in the request.args

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM