Good day, in addition to having a problem, what I think I have is a theoretical doubt: I have been making a system with several CRUDs applying the MVC model . In all my CRUDs I follow the same steps: file.php which makes the call to controller.php just before the closing of the tag form
, controller.php processes and verifies the data, sends it to model.php and it does its thing by communicating with the DB.
What happens to me in the last CRUD is that the button submit
of this form, in addition to submitting it, has a couple of actions onClick
in a .js file .
I mention this about the actions JS
because it is the only button submit
of all my forms that has this type of behavior, and the CRUD does not work (specifically the Creation of elements)
I strongly suspect that it has something to do with the fact that the button executes actions in JS
, but I'm not sure and that's why I'm missing something. I would appreciate it if you could help me.
Here is my code:
create-menu.php
<div class="card-footer">
<button type="submit" class="botonGuardar">Guardar Menú</button>
</div>
</form>
<?php
$crearMenu = new ControladorViandas();
$crearMenu -> ctrCrearVianda();
?>
EDIT 1 : I have already tried putting this code php
both inside and outside the tags form
, with the same result in both attempts.
menu.js with this action, I collect data from the form and save it as an string
in val
of an element of my html
, to collect it later with the variables $_POST[]
. I don't know if it's a good idea.
$(".botonGuardar").click(function() {
// Creo el objeto JSON
listaIngredientes = [];
$(".listaIngredientes").each(function() {
var ingrediente = $(this).children(".col-6").children().children(".nuevoNombreIngrediente").val();
var cantidad = $(this).children(".col-2").children(".nuevaCantidadIngrediente").val();
var precio = $(this).children(".ingresoPrecio").children().children(".precioIngrediente").val();
var unidad = $(this).children(".div-unidad").children(".unidad-de-medida").val()
listaIngredientes.push({
"ingrediente": ingrediente,
"cantidad": cantidad,
"unidad": unidad,
"precio": precio
})
})
$("#ingredientesFinal").val(JSON.stringify(listaIngredientes));
});
controller.php As you can see, there are some console messages js
in the php code . When I go to create-menu.php the console throws a "there is no post new menu variable", but when I send the form it doesn't throw any of the two consoles. It's like it never reruns the method to create a new menu/package
static public function ctrCrearVianda(){
if(isset($_POST["nuevoMenu"])){
echo '<script>console.log("hay variable post nuevo menu")</script>';
if( preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚüÜ ]+$/', $_POST["nuevoMenu"])) {
$tabla = "viandas";
$datos = array(
"nombre" => $_POST["nuevoMenu"],
"id_cliente" => $_POST["seleccionarCliente"],
"productos" => $_POST["ingredientesFinal"],
"costo" => $_POST["nuevoPrecioMenu"],
"dmc" => $_POST["nuevoDmc"]
);
$respuesta = ModeloViandas::mdlCrearVianda($tabla,$datos);
if($respuesta == "ok"){
// El menu se creó correctamente
echo '<script>
swal.fire({
type: "success",
title: "El menu ha sido creado correctamente",
showConfirmButton: true,
confirmButtonText: "Cerrar",
closeOnConfirm: false
}).then(function(result){
if(result.value){
var url = window.location
var parts = url.toString().split("/");
var lastSegment = parts.pop() || parts.pop();
window.location = lastSegment;
}
});
</script>';
}
}else{
//EL NOMBRE DE MENU NO PUEDE LLEVAR CARACTERES ESPECIALES
}
}else{
echo '<script>console.log("no hay variable post nuevo menu")</script>';
}
}
model.php Finally I leave the model, although it is in vain because I am almost sure that it is fine, and also the error returned by the system means that it does not directly interact with this file.
/*============================================
CARGAR VIANDA
============================================*/
static public function mdlCrearVianda($tabla, $datos){
$stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(nombre, id_cliente, productos, costo, dmc) VALUES ( :nombre, :id_cliente, :productos, :costo, :dmc)");
$stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR);
$stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_STR);
$stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR);
$stmt->bindParam(":costo", $datos["costo"], PDO::PARAM_STR);
$stmt->bindParam(":dmc", $datos["dmc"], PDO::PARAM_STR);
if($stmt->execute()){
return "ok";
}else{
return "error";
}
$stmt -> close();
$stmt = null;
}
Hello @Mani I am going to try an unorthodox answer but one that I usually use when I need certain behaviors prior to submitting the forms:
By binding (binding () ) the desired behavior to the click event , you are adding it to your normal behavior, so both behaviors are going to fire. To prevent the default behavior from being launched first, or both from being executed without knowing for sure which one is going first, you must start by untying the default behavior (in this case, triggering the submit of the form) like this:
In this way you have a simple solution that ensures that the submission of the form is done with the data properly prepared.
You can place an event.prevenDefault() and there add the data you want to add and then do the submit...