0

I am trying to change the content in a div by clicking on the div. The request is sent with Ajax to a python script which sends a ssh request and then result is returned.

My problem is that it seems like the first klick sends the request and a second click returns the data. So if I click the first div nothing happens and on the second click the data from the first click is populated in the next div I click on.

Could it be that the ssh request takes to long so the ajax script is done before the response is returned?

Is it possible to return data directly from the python script to the Ajax script instead of first sending it to response.html?

ap.py

@app.route('/_get_data/', methods=['POST'])
def _get_data():
    vlan = request.form.get('vlan')
    result = str(SSHConnection("172.16.0." + str(vlan) ,"command"))
    return jsonify({'data': render_template('response.html', result = result)})

index.html

$(document).ready(function() {
  $(".p-1").on('click', function(event) {
    var vlan;
    vlan = event.target.id;
    $.ajax({
      url: "/_get_datan/",
      type: "POST",
      data: {
        vlan
      },
      success: function(resp) {
        result = (resp.data);
      }
    });
    document.getElementById(event.target.id).innerHTML = result;
  });
});
<div class="col">
  <div class="p-1 border bg-light" align="center" id="101">101 <i class='fas fa-power-off' style='color:#eeeeee'></i></div>
</div>
<div class="col">
  <div class="p-1 border bg-light" align="center" id="102">102 <i class='fas fa-power-off' style='color:#eeeeee'></i></div>
</div>
<div class="col">
  <div class="p-1 border bg-light" align="center" id="103">103 <i class='fas fa-power-off' style='color:#eeeeee'></i></div>
</div>

response.html

{{result}}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Tobbe
  • 55
  • 7
  • 1
    `document.getElementById(event.target.id).innerHTML = result;` should be inside the `success` function. – Barmar Mar 05 '21 at 17:42
  • AJAX is asynchronous, so you're using the `result` variable before this AJAX call has completed. As a result, you're getting the value left over from the previous call. – Barmar Mar 05 '21 at 17:46

0 Answers0