-1

I have this python app using flask having this core routes:

@app.route('/test_limit', defaults={'page':1})
@app.route('/test_limit/page/<int:page>')
def test_results_limit(page):
    perpage=10
    startat=page*perpage
    results = []
    cursor = db.cursor()
    cursor.execute('SELECT * from pi_fb_limit limit %s, %s;', (startat,perpage))
    table = list(cursor.fetchall())
    return render_template('results_limits.html', table=table)

@app.route('/infringement/FB/<int:id>')
def infringement(id):
    cursor = db.cursor()
    cursor.execute('UPDATE p_test_search SET infringement = ''TRUE'' WHERE ID = %s', (id))  
    db.commit()
    return render_template('results_limits.html')

In my HTML file "result_limits.html" I have this HTML code iterating MySQL resoult:

 </table>
<tbody>
         {% for tab in table %}
            <tr class="zoomin">
               <th> {{tab[0]}} </th>
               <td> {{tab[9]}} </td>
               <td><button type="button" onclick="location.href='/infringement/FB/'+{{tab[0]}};return false;" class="btn btn-danger">Infringement</button></td>
            </tr>   
         {% endfor %}
        </tbody>
  </table>

All is working fine but my problem is that when the button above dinamically call the route @app.route('/infringement/FB/'), browser is redirected to result_limits.html. Instead I'd like to avoid any redirection and remain on the same page each row button is creating post (to update records).

Any suggestion? Thank you Regs SL

user3925023
  • 667
  • 6
  • 25

1 Answers1

1

You need to use JavaScript to submit data without reloading the page.

Something like:

function submit_infringement(id) {
  this.removeAttribute('onclick');  // Prevent sumbitting twice.
  var x = new XMLHttpRequest();
  x.open('GET', '/infringement/FB/' + id, true);
  x.onload = function() {
    this.textContent = 'Infringement report sent!';
  }
  x.onerror = function(error) {
    (console.error || console.log)(error);
    this.textContent = 'An error occured. Try again.';
    this.onclick = function() { sumbit_infringemet(id); }
  }
  this.textContent = 'Sending infringement report...';
  x.send(null);
}
<td>
  <button type="button" onclick="sumbit_infringement({{tab[0]}});" class="btn btn-danger">
    Infringement
  </button>
</td>
Artyer
  • 31,034
  • 3
  • 47
  • 75