-1

I want render a new template after jQuery ajax post request. How can I do this when I make the request with jquery/ajax?

Here is the initial route from where post request is sent.

@app.route("/data")
def data():
if request.method=='GET':
    cursor.execute("SELECT * from data")
    data = cursor.fetchall()
    cursor.execute("DESCRIBE data")
    headers = cursor.fetchall()
    return render_template("data.html", data=data, headers=headers)

Here is jQuery in data.html that sends the request

...
<script>
  $(document).ready(function(){
    $('.row').each(function(){
      $(this).click(function(){
        let rowId = $(this).attr('id');
        var data_send = {'id' : rowId};
        $.ajax({
          type:'POST',
          url: '{{ url_for('row') }}',
          data : JSON.stringify(data_send),
          dataType: "json"
        })
      })
    })
  });
</script>

This is the method that receives the post request:

@app.route('/row', methods=['POST'])
def row():
    recieved_data = request.get_data().decode('utf8')
    target_id = json.loads(recieved_data)['id']
    cursor.execute("DESCRIBE data")
    headers = cursor.fetchall()
    cursor.execute("SELECT * from data")
    data = cursor.fetchall()[int(target_id)]
    return render_template("row.html",data = data, headers=headers)

Even though the server receives the post request with no problem, the browser is not redirected to row.html. I don't want to send back a redirect URL and JSON, but actually render a template.

enryu
  • 3
  • 1
  • 3

2 Answers2

0

The view function does not allow GET requests, so the browser can not open row.html.

try

@app.route('/row', methods=['GET', 'POST'])
def row():
    data = None
    headers = None
    if request.methods == 'POST':
        recieved_data = request.get_data().decode('utf8')
        target_id = json.loads(recieved_data)['id']
        cursor.execute("DESCRIBE data")
        headers = cursor.fetchall()
        cursor.execute("SELECT * from data")
        data = cursor.fetchall()[int(target_id)]
    return render_template("row.html",data = data, headers=headers)
Shy
  • 1
  • 2
0

You can set html attribute from ajax response with html rendered template, like $('#some_id').html(response). See following example for details:

...
<script>
  $(document).ready(function(){
    $('.row').each(function(){
      $(this).click(function(){
        let rowId = $(this).attr('id');
        var data_send = {'id' : rowId};
        $.ajax({
          type:'POST',
          url: '{{ url_for('row') }}',
          data : JSON.stringify(data_send),
          dataType: "json",
          success: function(response) {
            $(this).html(response);
          }
        })
      })
    })
  });
</script>
wowkin2
  • 5,895
  • 5
  • 23
  • 66