How my javascript can get json result returned by Flask Python route?

163 views Asked by At

I have a flask web application with python.

I have a template where user have a list of tasks with checkboxes to enable or disable the task. I use jsonify and javascript to update or disable the value in Mysql database.

here is the route:

@app.route('/update_enable_task_user', methods=['GET', 'POST'])
@login_required
def update_enable_task_user():
    print(f"update_enable_task_user request.form : {request.form}")
    taskuser = TaskUser.query.filter_by(id=int(request.form['id_task_user'])).first()
    print(f"request.form['enable'] : {request.form['enable']} - {type(request.form['enable'])}")
    

    if request.form['enable'] == "1":        
        return jsonify({'result':'failed'})

    else:
        return jsonify({'result':'success'})

Here is the template:

<div id="enable_disable_task_2"> 
    <label><input type="checkbox" onclick="checktaskuser()" class="ios-switch switch green" id="platform_task_2_enable" platform_id_task_user="2" name="platform_task_2_enable"
        style="opacity: 0;"/>
        <div>
            <div></div>
        </div>
    </label>
    
</div>

function checktaskuser(){
    var taskuser_update =  document.getElementById("platform_task_{{task[5]}}_enable");
    var url= window.location.href;
    alert(taskuser_update);
    if ( document.getElementById("platform_task_{{task[5]}}_enable").checked === false ) {
        alert("platform_task_{{task[5]}}_enable is NOT checked!!!!");
    
        
                
        var data;
        $.ajax({
            dataType: "json",
            url: url,
            data: data,
            success: function (data) {
                // begin accessing JSON data here
                alert(result);
            }
        });
    }
        
}

When My user check the checkbox, I see the 2 alert messages from javascript and I can see the json in network tab of browser console: enter image description here

So for me, that means my flask python script did the job. But it failed somewhere in ajax?

But the 3rd alert in my javascript (alert(result);) is not showing up. I don't see any error messages (not in the Chrome console and not from the Flask console).

So I tried the getJSON function :

function checktaskuser(){
                    var taskuser_update =  document.getElementById("platform_task_{{task[5]}}_enable");
                    var url= window.location.href;
                    alert(taskuser_update);
                    if ( document.getElementById("platform_task_{{task[5]}}_enable").checked === false ) {
                        alert("platform_task_{{task[5]}}_enable is NOT checked!!!!");
                    
                        
                                
                        $.getJSON(
                            url ,
                        function(data) {
                            $('#result').textalert(data);
                        }
                    );
                    }
                        
                }

And I get same result: No 3rd alert and no error message.

EDIT 1:

After thinking of my issue, I think the javascript is executed before the FLask route is executed. That is why the json is empty as it was not sent yet by Flask route.

So my question is how my javascript can catch the json returned by FLask python route?

EDIT 2

I tried the solution of @folan

I get "Uncaught ReferenceError: data is not defined in console.

enter image description here So my question is What is data? I am not an expert at all in jquery and javascript. I am trying to make work Python with javascript on a page which updata Mysql database without refreshing.

When user is on template page, he can update the column "enable" on Mysql DB without refreshing the page.

Flask update the Mysql DB on a special route.

@app.route('/update_enable_task_user', methods=['GET', 'POST'])
@login_required
def update_enable_task_user():

My new question is What is "data"? It suppose to be the jsonify sent by Flask route which I caught. But Ajax seems not to catch the data in this solution.

I didn't declare it in my code and this $ajax() formula intrigues me. So I read the doc https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f

I didn't show the part of Flask code in template which call the flask route: Jquery code & Flask to Update the column "enable" task in Mysql DB.

// ===================== TASK ENABLE WITH ID =================================        
            var platform_id_task_user = {{task[5]}};
            // When user check the check box task_enable
            $('#platform_task_{{task[5]}}_enable').on('change', function() {                
                
                // We collect the ID of task_user
                
                // if task_enable is checked
                if ($('#platform_task_{{task[5]}}_enable').is(':checked')){                    
                    var task_enable = 1;           
                }
                // if task_enable is NOT checked
                else{                    
                    var task_enable = 0;
                }
                // We send the data to our route update_enable_task_user
                req = $.ajax({
                    url : '/update_enable_task_user',
                    type : 'POST',
                    data : {enable : task_enable,id_task_user: {{task[5]}}}
                });
                $('#enable_disable_task_{{task[5]}}').fadeOut(1000).fadeIn(1000);
            });

In this code above, we can see the "data" variable. Maybe should I add my code here. Instead of creating the function :

onclick="checktaskuser()"

Should I add my code here? I did try with an alert to display the "data" but I get again "Uncaught ReferenceError: data is not defined"

1

There are 1 answers

3
frx On

You can listen to your ajax request and on its completion, you can execute your success callback.

var call = $.ajax({
  dataType: "json",
  url: url,
  data: data,
});

// Listening to completion
call.done(function(data){
  alert(data);
});

You can read more about ajax https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f