0

How to use ajax callbacks with jquery datatables i.e. call function on click?:

THIS WORKS

$(document).ready(function() {
    var table = $('#example').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        var data = table.row( this ).data();
        alert( 'You clicked on '+data[0]+'\'s row' );
    } );
} );

replacing alert( 'You clicked on '+data[0]+'\'s row' ); with Ajax call:

DOES NOT WORK

$(document).ready(function() {
    var table = $('#example').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        var data = table.row( this ).data();
        //alert( 'You clicked on '+data[0]+'\'s row' );

         $.ajax({
                url: '/process',
                data: data[0],
                type: 'POST',
                success: function(response) {
                    $("#response_placeholder").html(response);
                },
                error: function(error) {
                    console.log(error);
                }
         });

    } );
} );

backend

#--app.py----

@app.route('/process', methods=['POST'])
def process_data():
    data =  request.form['data[0]'];
    print data
    return render_template('mypage.html', result=data)

1 Answer 1

3

try to use this.

 $('body').delegate('#example tbody tr','click' , function () {


} );

Delegate helps to add events on elements that get added to the dom after it has been loaded.

also it is handy to put the data in an object like this

data: {data: data[0]},

and the url should contain a extension probably

url: '/process.js', // or process.php depends on what extension it has.

and for standards you should define the 3 attributes that will be returned with error eg.

error: function(jqXHR, textStatus, errorThrown) {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.