estoy haciendo un dashboard que contiene una tabla con usuarios y la posibilidad de crearlos. Cuando los creo basicamente se abre un modal de bootstrap con un formulario.
El formulario lo uso con ajax y nodejs como server. Funciona todo a la perfeccion pero el unico problema es que el modal de bootstrap no se cierra automaticamente cuando la operacion finaliza. Intente con muchos metodos como el hide(), toggle() etc, pero no logro que se cierre.
Mi codigo ajax es una funcion que recopila los datos, los envia a node y en base a la respuesta muestra una alerta de sweetalert2. Al final, como ven, intento cerrar el modal. Esto fue lo que "mas" me funcionó porque cierra el modal pero me bloquea el scroll de la web hasta que la recargue.
$('#form_create').submit(function (e) {
e.preventDefault();
let username_c = $.trim($('#username_c').val());
let email_c = $.trim($('#email_c').val());
let rol_c = $.trim($('#rol_c').val());
let password = $.trim($('#password').val());
let password_c = $.trim($('#password_c').val());
$.ajax({
url: 'http://localhost:3001/create_user',
method: 'post',
contentType: 'application/json',
data: JSON.stringify({ username: username_c, email: email_c, rol: rol_c, password: password, password_confirm: password_c }),
success: function (data) {
if (data.auth == false) {
Swal.fire({
title: 'Error',
text: `The user ${data.username} already exist`,
icon: 'error',
showConfirmButton: true,
timer: false
});
} else if (data.password == false) {
Swal.fire({
title: 'Warning',
text: `The password doesnt match`,
icon: 'warning',
showConfirmButton: true,
timer: false
});
} else if (data.fields == false) {
Swal.fire({
title: 'Warning',
text: `Complete all fields please`,
icon: 'warning',
showConfirmButton: true,
timer: false
});
} else if (data.auth == true) {
Swal.fire({
title: 'Success',
text: `User created succesfuly`,
icon: 'success',
showConfirmButton: false,
timer: 1500
});
datatable.ajax.reload(null, false);
}
}
});
myModal.hide();
$('.modal-backdrop').remove();
})
});
El modal lo declaro en el script como:
var myModal = new bootstrap.Modal(document.getElementById('exampleModalCenter'));
Y finalmente mi modal con el boton que lo abre:
<div class="ml-4 mt-3">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModalCenter">Create</button>
</div>
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Create user</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="form_create">
<div class="form-floating mb-3">
<input id="username_c" name="username" class="form-control" type="text"
placeholder="Enter Username" />
<label for="username_c">Username</label>
</div>
<div class="form-floating mb-3">
<input id="email_c" name="email" class="form-control" type="email"
placeholder="[email protected]" />
<label for="email_c">Email address</label>
</div>
<div class="row mb-3">
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input id="password" name="password" class="form-control" type="password"
placeholder="Create a password" />
<label for="password">Password</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input id="password_c" name="password_confirm" class="form-control" type="password"
placeholder="Confirm password" />
<label for="password_c">Confirm Password</label>
</div>
</div>
</div>
<div class="form-floating mb-3">
<input id="rol_c" name="rol" class="form-control" type="text" placeholder="Rol" />
<label for="rol_C">Rol</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Discard</button>
<button id="btn_close" type="submit" class="btn btn-primary">Create</button>
</div>
</form>
</div>
</div>
</div>
Cabe destacar que tambien intente borrar las clases pero si lo hago luego no me permite volver a abrir el modal.
Agregro mi servidor node
App
import express from 'express';
import { engine } from 'express-handlebars';
import session from 'express-session';
import bodyParser from 'body-parser';
import MySQLStore from 'express-mysql-session';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { router } from './routes/routes.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const PORT = "3001";
var options =
{
host: 'localhost',
port: '3306',
user: 'root',
password: '',
database: 'dashboard'
}
var sessionStore = new MySQLStore(options)
app.listen(PORT, () => {
console.log("SERVER WORKING");
})
app.engine('hbs', engine
({
extname: ".hbs",
helpers:
{
conditional_helpdesk: (rol) => {
if (rol == 'Help Desk') {
return true;
} else {
return false;
}
},
conditional_admin: (rol) => {
if (rol == "Administrador") {
return true;
} else {
return false;
}
}
}
}));
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, '../views'));
app.use(express.static(path.join(__dirname, '../public')));
app.use(session({
key: 'session_info',
secret: 'secret',
store: sessionStore,
resave: false,
saveUninitialized: false
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
next();
});
app.use(router);
ROUTES
import express from 'express';
import { Router } from 'express';
import { controller } from '../controllers/index_controller.js'
import { admin_controller } from '../controllers/admin_controller.js'
const router = express.Router();
router.get('/', controller.login_redirect);
router.post('/auth', controller.login_auth);
router.post('/create_user', controller.register_createUser);
router.get('/logout', controller.logout);
router.get('products', controller.products_noLogin);
router.get('/tables', controller.tables_view)
router.get('/charts', controller.charts_view)
router.get('/register', controller.register_view)
router.get('/tables_ajax', admin_controller.ajax_table_show);
router.put('/tables_ajax:id', admin_controller.ajax_table_edit);
router.delete('/tables_ajax:id', admin_controller.ajax_table_delete);
export {router}
CONTROLLER DEL MODAL
controller.register_createUser = async (req, res) => {
var username = req.body.username;
var password = req.body.password;
var password_confirm = req.body.password_confirm;
var email = req.body.email;
var rol = req.body.rol;
var route = req.body.route;
var check = req.body.check;
if (route == undefined) {
route = 'register';
}
if (rol == null || rol == undefined) {
rol = 'User';
}
if(check == null || check == undefined){
check = false;
}
if (username && password && email && password_confirm && rol) {
if (password == password_confirm) {
const SQL_CHECK = "SELECT Username, Password, Rol FROM users_nodejs WHERE Email = ?";
connector.query(SQL_CHECK, [email], async (error, result, fields) => {
switch (result.length) {
case 0:
let password_hash = await bcrypt.hash(password, 8);
const SQL_SENTENCE = "INSERT INTO users_nodejs SET ?";
connector.query(SQL_SENTENCE, { Username: username, Password: password_hash, Email: email, Rol: rol },
async (err, results) => {
if (error) {
throw error;
} else if(check) {
res.render('products',
{
Loggedin: true,
Username: result[0].username
});
}else{
res.json(
{
auth: true
}
);
}
})
break;
case 1:
res.json({
auth: false,
username: result[0].Username
})
break;
}
});
} else {
res.json({
password: false
})
}
} else {
res.json({
fields: false
})
}
}
Aqui aclaro que este controller lo uso para que se registren usuarios y para que el administrador cree usuarios, para distinguir ambas acciones uso la variable check
que envio con ajax
id
en todos los inputs, eso no puede ser bueno, 2) Cierras un div (</div>
) de más antes del</form>
... 3) No has puesto como llamas al modal, el botón que lo llama al menos 4) Tienes un doble cierre en el javascript, al final de todo, no se, revisa bien eso y si el problema continua lo miramos de nuevo pero antes edita la pregunta con el codigo arregladomyModal.hide();
deberías usar$("exampleModalCenter").hide();
. Prueba y nos cuentas.$(document).ready({ })
. El problema persiste.$('#exampleModalCenter').modal('hide')
, que es la sintaxis correcta para los modales en bootstrap 4. Y quita lo del$('.modal-backdrop').remove();
pues ya se hace automaticamente con esa instrucción. Aquí parece funcionar: jsfiddle.net/3roybxuh