FLASK unboundlocal error, while navigate through another page

when i click on the username, it has to navigate to another page with the particular user information. to acheive this i tried with jquery, python and flask. But i was not able to achieve it, i get the error below.

FLASK unboundlocal error, while navigate through another page

Can anyone please help me. Is their anything wrong in the code.

Below is the code

app.py

app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
       userid = request.form['userid']
       cur.execute("SELECT * FROM user WHERE id = %s", [userid])
       result = cur.fetchall() 
    return render_template('detail.html', result=result)

index.html

 {% for row in emp %}    
  <tr>                
        <td>{{row.id}}</td>  
         <td><a data-id='{{row.id}}' class="userinfo btn btn-success" href="{{ url_for('ajaxfile') }}">{{row.name}}</a></td>  
  </tr>
  <script type='text/javascript'>
        $(document).ready(function(){
            $('.userinfo').click(function(){
                var userid= $(this).data('id');
                alert(userid)
                $.ajax({
                    url: '/ajaxfile',
                    type: 'post',
                    data: {userid: userid},
                    success: function(data){ 
                        
                    }
                });
            });
        });
</script>

details.html

 {% for row in result %} 
 <table border='0' width='100%'>
 <tr>     
    <td style="padding:20px;">
    <p>Name : {{row.name}}</p>
    <p>Description : {{row.description}}</p>
    <p>Responsible person : {{row.responsibleperson}}</p>
    <p>Employee code : {{row.employeename}}</p>
    <p>Date : {{row.date_time}}</p>
    </td>
 </tr>
</table>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The error is self explanatory that you used variable result , before defining.

You are making ajax request to send data to flask. If you return any data within the if scope then it is stored in data param of success function in js.

You can’t render_template in that way, you have two options

  1. You should send data using forms, after which you can use return render_template() function in if scope. But you can’t visit the detail page without a post request from index.html
  2. You can send data using ajax and return the result variable in if scope.return jsonify{"res":result}, now data has the json and data.res has value of result in success function. You can use the for loop of javascript and append data using jquery on the same page.
    Make a td tag , give it Id and use it in jquery.

If you give the full code , I can edit it and send or post it here. through github or discord.

edit: You can do it like this.

from flask import jsonify 
app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
       userid = request.form['userid']
       cur.execute("SELECT * FROM user WHERE id = %s", [userid])
       result = cur.fetchall()
       return jsonify{result=result}
    return "Hello world" # to avoid error, you can also allow only post methods by removing get from methods.

in html: You have to do this in the index.html file.

[...] 
<table border='0' width='100%'>
 <tr>     
    <td style="padding:20px;" id="my_td">
    
    </td>
 </tr>
</table>

js: In success function.

 success: function(data){ 
   for (row of data.result){
   $("#my_td").append(`<p>Name : row.name</p><p>Description : row.description</p><p>Responsible person : row.responsibleperson</p><p>Employee code : row.employeename</p><p>Date : row.date_time</p>`)                           
      }
 }

Method 2 Using Forms

Html : make a form tag and an hidden input whose value will be row.id

{% for row in emp %}    
<tr>
     <form action="/ajaxfile" method="POST">
          <input value="{{row.id}}" type="hidden" name="userid">
       <td>{{row.id}}</td>
     <td><button data-id='{{row.id}}' type="submit" class="userinfo btn btn-success" >{{row.name}}</button></td>
     </form>
</tr>
{% endfor %}

Python: Keep everthing same and return render_template in if scope.

[...]
if request.method == 'POST':
     [...]
     return render_template('detail.html', result=result)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x