I have a problem with ajax calls in JQuery

0

I'm doing an application with php and JQuery and I use and use JQuery to make ajax requests to load some parts of the page and I have a problem when I'm going to register a new book using the panel that I created for that, when I register a book for the first time it is normal, but when I do it again it registers it twice and if I do it again it is done more than twice and so on ...

This is the registration panel code:

<?php
require_once "comprobar_in.php";
require_once "conexion.php";
?>

<header>
<h3 id="tocar">Registrar libro <span id="salir_rl">X</span></h3>
</header>

<form id="frm_reg_lib">

<div class="campo-formulario">
<label for="nombre">Nombre:</label>
<input type="text" maxlength="50" name="nombre" id="nombre" required />
</div>

<div class="campo-formulario">
<label for="autor">Autor:</label>
<input type="text" maxlength="50" name="autor" id="autor" required />
</div>

<div class="campo-formulario">
<label for="estado">Estado:</label>

<div id="c_estado">

  <label for="radio" class="estado">Disponible</label>
  <input type="radio" maxlength="50" name="estado" id="estado" class="estado" required value="Disponible"  checked />

  <br />

  <label for="radio" class="estado">No disponible</label>
  <input type="radio" maxlength="50" name="estado" id="estado" class="estado" value="No disponible" required />
  </div>
  </div>

  <div class="campo-formulario">
  <label for="codigo">Código:</label>
  <input type="text" maxlength="50" name="codigo" id="codigo" required />
  </div>

<div class="campo-formulario">
   <label for="tipo">Tipo:</label>
   <input type="text" maxlength="50" name="tipo" id="tipo" required />
</div>

<div class="campo-formulario">
  <label for="editorial">Editorial:</label>
  <input type="text" maxlength="50" name="editorial" id="editorial" required />
</div>

<div class="campo-formulario">
  <button type="button" class="boton" id="btn_registrar_libro">Registrar</button>
</div>
</form>
<?php 
 require_once "agregar_script.php";
 ?>

content of registro_libro.php:

<?php 
require_once "conexion.php";

$nombre    = $_POST['nombre'];
$autor     = $_POST['autor'];
$estado    = $_POST['estado'];
$codigo    = $_POST['codigo'];
$tipo      = $_POST['tipo'];
$editorial = $_POST['editorial'];

// $nombre    = 'qwe';
// $autor     = 'qwe';
// $estado    = 'Disponible';
// $codigo    = 'qwe';
// $tipo      = 'qwe';
// $editorial = 'qwe';

if($_SERVER['REQUEST_METHOD'] == 'POST'){
$consulta = $conexion->query("INSERT INTO libros (nombre, autor, estado, codigo, tipo, editorial) VALUES ('$nombre', '$autor', '$estado', '$codigo', '$tipo', '$editorial')");
if ($consulta) {
echo "exitoso";
}else{
 echo "error";
}
}
?>

and this is the JQuery code that I use to load the pages with ajax:

/**
* Registrar nuevo libro
*/

$("#btn_registrar_libro").on("click", function(){
$formulario = $("#frm_reg_lib").serialize();
$.post("registrar_libro.php", $formulario, function(result){
  alert("El libro se agregó correctamente");
if (result == "exitoso") {
  $("#nombre").val("");
  $("#autor").val("");
  $("#codigo").val("");
  $("#tipo").val("");
  $("#editorial").val("");
  $("#tabla").load("tabla.php");
}else if (result == "error") {
  alert("Hubo un problema al registrar el libro");
}
});
});

/**
* Barra de navegación
*/


$("#home").on("click", function(e){
e.preventDefault();
$("#home").removeClass("boton_nav");
$("#home").addClass("activa");
$("#libros, #registros").removeClass("activa");
$("#libros, #registros").addClass("boton_nav");
});

$("#libros").on("click",function(e){
e.preventDefault();
$("#libros").removeClass("boton_nav");
$("#libros").addClass("activa");
$("#home, #registros").removeClass("activa");
$("#home, #registros").addClass("boton_nav");
$("#contenido").load("libros.php");
});

$("#registros").on("click",function(e){
e.preventDefault();
$("#registros").removeClass("boton_nav");
$("#registros").addClass("activa");
$("#home, #libros").removeClass("activa");
$("#home, #libros").addClass("boton_nav");
$("#contenido").load("registros.php");
});

/**
* Mostrar panel para registrar libro
*/

$("#registrarL").on("click", function(e){
e.preventDefault();
$("#registrarL").hide("1000");
$("#reg_libro").show("1000");
});

/**
* Ocultar panel para registrar
*/

$("#salir_rl").on("click", function(){
$("#reg_libro").hide("1000");
$("#registrarL").show("1000");
});
    
asked by Mac32 08.04.2018 в 05:33
source

1 answer

0

At present you can not see incorrect logic or code errors if you show wrong behavior, it's not because of the exposed code, the only serious detail is that your code is prone to receive SQL injection attacks , which is the closest consequence of concatenating values directly to the executed query.

I propose to prepare the query to give you more security, with mysqli_prepare , these details were taken in account and are explained more in detail in the following question How to avoid SQL injection in PHP?

require_once "conexion.php";

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $nombre    = $_POST['nombre'];
    $autor     = $_POST['autor'];
    $estado    = $_POST['estado'];
    $codigo    = $_POST['codigo'];
    $tipo      = $_POST['tipo'];
    $editorial = $_POST['editorial'];
    //Preparamos la consulta , para luego bindear los valores recibidos por POST
    if ($sentencia = $conexion->prepare("
            INSERT INTO libros (nombre, autor, estado, codigo, tipo, editorial) 
            VALUES (?, ?, ?, ?, ?, ?)")) 
    {
        /* bindear los  parámetros para marcadores, asumo que todos son Strings */
        $sentencia->bind_param("ssssss", $nombre, $autor,$estado,$codigo,$tipo,$editorial);
        /* ejecutar la consulta */
        if($sentencia->execute()) {
            echo "exitoso";
        }else{
            echo "error";
        }
        $sentencia->close();
    }
    $conexion->close();
}

In addition to the JQuery side you can reset the form directly and avoid clearing each field

$("#btn_registrar_libro").on("click", function(){
    $formulario = $("#frm_reg_lib").serialize();
    $.post("registrar_libro.php", $formulario, function(result){
        alert("El libro se agregó correctamente");
        if (result == "exitoso") {
            $("#frm_reg_lib")[0].reset(); //Limpiar el form
            $("#tabla").load("tabla.php");
        }else if (result == "error") {
            alert("Hubo un problema al registrar el libro");
        }
    });
});
    
answered by 08.04.2018 / 06:09
source