5

I have a jQuery datatable that I use to display data after making a AJAX request. However, I want to add a third column to the table if the current user is an administrator so that they can delete an entry. How would I add a third column based on a conditional statement? Thanks.

Code:

    // Create our AJAX request to get the data
    new Ajax.Request( combat_record_link,
    {
        method: 'get',
        evalJSON: 'force',
        parameters: {
            'md5check': ipb.vars['secure_hash']
        },
        onSuccess: function(t)
        {
            if( Object.isUndefined( t.responseJSON ) )
            {
                alert( "Bad Request" );
            }
            else if ( t.responseJSON['error'] )
            {
                alert( t.responseJSON['error'] );
            }
            else
            {
                jQuery('#combat_record').dataTable( {
                    "data": t.responseJSON,
                    "paging": true,
                    "ordering": true,
                    "order": [[ 0, "desc" ]],
                    "info": false,
                    "columns": [
                        { "title": "Date", "width": "10%", "data": "date"},
                        { "title": "Entry", "width": "90%", "data": "entry", "orderable": false},
                    ]
                });                 
            }
        }
    });
1
  • Thanks for asking this question, it helped me. Please be responsible to accept the working answer. Commented Jan 13, 2021 at 3:46

1 Answer 1

13

You can just do:

var columns = [{ "title": "Date", "width": "10%", "data": "date"},
               { "title": "Entry", "width": "90%", "data": "entry", "orderable": false}];

if(isAdmin){
   columns.push({"title": "Delete", ...});
}

jQuery('#combat_record').dataTable( {
                    "data": t.responseJSON,
                    "paging": true,
                    "ordering": true,
                    "order": [[ 0, "desc" ]],
                    "info": false,
                    "columns": columns
});
Sign up to request clarification or add additional context in comments.

2 Comments

This should be the accepted answer. Worked perfectly, thanks!
Thank you! I don't know why the answer is not accepted yet.

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.