0

Necesito ejecutar una función como respuesta al evento click en una columna de DataTables. Cuando activo el botón editar me arroja un error:

Uncaught ReferenceError: editUser is not defined

Las importaciones funcionan perfectamente. La carga de datos funciona de igual manera: bien.

La carga de ajax se realiza correctamente también. En otras palabras, llegan datos perfectamente de la base de datos.

Tan solo es que no me reconoce la función editUser. Aunque el html que genera es correcto.

"use strict";

import {pageTitle, base_url, toastSwal} from '../common/config'
import {lang, defaultLang} from '../common/language'
import {sidebar} from '../index/sidebar'

$(document).ready( _ => {
  pageTitle(lang().welcome.welcome)
  $('#navbarLogout').text( lang().navbar.logout )
  $('#navbarContact').text( lang().navbar.contact )

  $('#usersPageTitle').text( lang().users.users )
  $('#usersBreadCrumb').text( lang().users.users )
  $('#usersNewUser').text( lang().users.newUser )



  $('#userTable').append(
    `<tfoot>
      <tr>
        <th>${lang().users.thId}</th>
        <th>${lang().users.thFirstName}</th>
        <th>${lang().users.thlastName}</th>
        <th>${lang().users.thUserName}</th>
        <th>${lang().users.thRoll}</th>               
        <th>${lang().users.thStatus}</th>
        <th>${lang().users.thPosition}</th>
        <th>${lang().users.thEmployeesEmail}</th>
        <th>${lang().users.thCreatedAt}</th>
        <th>${lang().users.thUpdatedAt}</th>
        <th>${lang().users.thActions}</th> 
      </tr>
    </tfoot>`
  );

  sidebar()
});


$('#userTable').DataTable({
  serverSide: false,
  ajax: {    
    async: true,
    url: 'ajaxGetAll.php',
    type: 'POST',
  },
  columns: [
    {data: "userId", title: lang().users.thId},
    {data: "firstName", title: lang().users.thFirstName},
    {data: "lastName", title: lang().users.thlastName},
    {data: "userName", title: lang().users.thUserName},
    {data: "rollName", title: lang().users.thRoll},
    {data: "status", title: lang().users.thStatus},
    {data: "position", title: lang().users.thPosition, defaultContent: lang().users.notAvailable},
    {data: "employeesEmail", title: lang().users.thEmployeesEmail},
    {data: "userCreatedAt", title: lang().users.thCreatedAt},
    {data: "userUpdatedAt", title: lang().users.thUpdatedAt},
    {defaultContent: '', render: (data, type, row, meta) =>     
    {    
      
      return `
      <button onclick="return editUser(${row.userId});" class="btn btn-outline-primary" title="${lang('es').users.edit} ${row.firstName} ${row.lastName}"><i class="fa fa-edit"></i></button>
      <a type="button" onclick="return deleteUser(${row.userId})" class="btn btn-outline-danger" title="${lang('es').users.delete} ${row.firstName} ${row.lastName}"><i class="fa fa-trash"></i></a>
   `},
   title:lang().users.thActions
    }, 
  ],
  columnDefs: [     
    { targets: 5,
      data: null,
      defaultContent: '',
      orderable: true,
      className: 'select-checkbox'
    }
  ],
  order: [[ 0, 'desc' ]],
  language: {
    url: base_url('common/inc/dataTables_es_es.json'),
  }  
});

const editUser = id => {
  alert( id )
  
  return false;
}

3
  • Ejecutar me da el error "Cannot use import statement outside a module"
    – Duston
    el 14 sep. 2021 a las 13:32
  • Estas usando const para definir la funcion, asi que tienes que declararla antes de usarla. Puedes moverla antes de llamar el constructor de dataTables, o cambiar el const por var el 14 sep. 2021 a las 13:53
  • Camilo Gómez, he hecho lo que me propones, con idéntico resultado el 14 sep. 2021 a las 19:05

1 respuesta 1

1

La función está en un scope distinto, hazla global para tener acceso a ella.

En lugar de:

const editUser = id => /*...*/

Utiliza:

window.editUser = id => /*...*/
1
  • Mil gracias, llevo un día probando cosas. el 15 sep. 2021 a las 12:25

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.