How can I validate with my id in ajax?

0

I am faced with two problems related to it, to be shorter I have the solution for each of them separately.

The first one is: Add field in php; The second: Place a code and click on another side, button, space, etc. Show in an input the name of the code entered.

Now I want to combine those two and I can not ... Because it asks me for a unique ID since it can only be one by one, in the first one if it creates the field with the unique ID, and solve that ... Now I want it in the second one, when creating each field, show me a unique code.

In the query script.php is my page which should show, in this case, it works as I said show name by code and the name puts it, but duplicates the rest ...

consult.php

    <!DOCTYPE html>
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

            var contenedor      = $("#contenedor");
            var AddButton       = $("#agregarCampo");

            var x = $("#contenedor div").length + 1;
            var FieldCount = x-1;

            $(AddButton).click(function (e)
            {
                if(x)
                {
                  FieldCount++;
                  $(contenedor).append('<div class="added"><input type="text"  name="codigo[]" id="campo'+FieldCount+'" placeholder="Ingrese codigo ID '+ FieldCount +'"/><input type="text" name="nombre" id="nombre" value=""></div>');
                  x++;
                }
            return false;
            });

          });
</script>
</head>
<body>
  <div id="cliente">
<table>
  <tr>
    <td>
      Codigo
    </td>
  </tr>
  <tr>
    <td>
        <div id="contenedor">
              <div class="added">
                <input type="text" name="codigo[]" id="codigo" placeholder="Ingrese codigo ID" required/>
                <input type="text" name="nombre" id="nombre" value="">
              </div>
            </div>
      <p>
      <a id="agregarCampo" href="#">Agregar Campo</a>
      </p>

    </td>
  </tr>
</table>
</div>
    <script type="text/javascript" src="cliente.js"></script>
</body>
</html>

Now this is the client.js

$(function(){
   $('#cliente').on('blur','#codigo',function(){
      var valor = this.value;
      if(valor.length>=1){
         var consulta = $.ajax({
            type:'POST',
            url:'cliente.php',
            data:{codigo:valor},
            dataType:'JSON'
         });

         consulta.done(function(data){
            if(data.error!==undefined){
               $('#estado').html('Ha ocurrido un error: '+data.error);
               return false;
            } else {
               if(data.nombre!==undefined){$("#cliente #nombre").val(data.nombre);}
               return true;
            }
         });

      }
   });
});

And this is where the query does, client.php

<?php

$codigo=$_REQUEST['codigo'];
$conexion=mysqli_connect("localhost","root","QWEZXCasd123","colegio");
if (mysqli_connect_errno($conexion)) {
    echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
}

$registros=mysqli_query($conexion, "select * from estudiantes where estudiante_id='$_REQUEST[codigo]'") or
  die("Problemas en el select:".mysqli_error());

if ($reg=mysqli_fetch_array($registros))
{
  $return = array('nombre' => $reg['nombre_estudiante']);
} else {
  $return = array('nombre'=>'No existe el registro');
}
   die(json_encode($return));
?>

Below in the following code should appear the name of the user with that code.

    
asked by HerAsd 15.05.2016 в 23:37
source

1 answer

0

The truth to need to know why I did not give my need with the dynamic ID, I was in the need to ask in the forum in English, have already answered my question and resolved it, here is the answer by if someone else happens:

HTML / JS

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {

                var contenedor = $("#contenedor");
                var AddButton = $("#agregarCampo");

                $(AddButton).click(function (e) {
                    e.preventDefault();
                    var FieldCount = contenedor.children('div').length + 1;
                    $(contenedor).append('<div class="added">\
                                            <input type="text" class="codigo_input" placeholder="Ingrese codigo ID ' + FieldCount + '"/>\
                                            <input type="text" class="nombre_input" >\
                                          </div>');
                });

            });
        </script>
    </head>
    <body>
        <div id="cliente">
            <table>
                <tr>
                    <td>
                        Codigo
                    </td>
                </tr>
                <tr>
                    <td>
                        <div id="contenedor">
                            <div class="added">
                                <input type="text" class="codigo_input" placeholder="Ingrese codigo ID" required/>
                                <input type="text" class="nombre_input" value="">
                            </div>
                        </div>
                        <p>
                            <a id="agregarCampo" href="#">Agregar Campo</a>
                        </p>

                    </td>
                </tr>
            </table>
        </div>
        <script>
            $(function () {
                $('#cliente').on('blur', '.codigo_input', function () {
                    var $container = $(this).closest(".added");
                    var valor = $(this).val();

                    if (valor.length >= 1) {

                        var consulta = $.ajax({
                            type: 'POST',
                            url: 'cliente.php',
                            data: {codigo: valor},
                            dataType: 'JSON'
                        });

                        consulta.done(function (data) {
                            if (data.error !== undefined) {
                                $('#estado').html('Ha ocurrido un error: ' + data.error);
                                return false;
                            } else {
                                if (data.nombre !== undefined) {
                                    $container.find('.nombre_input').val(data.nombre);
                                }
                                return true;
                            }
                        });

                        consulta.error(function(a,b,c){
                            console.log(a);
                            console.log(b);
                            console.log(c);
                        });

                    }
                });
            });
        </script>
    </body>
</html>

And here's the PHP

$codigo = $_POST['codigo'];
$conexion = mysqli_connect("localhost", "root", "", "gabu");
if (mysqli_connect_errno()) {
    echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
}

$registros = mysqli_query($conexion, "select * from estudiantes where estudiante_id='$codigo'") or
die("Problemas en el select:" . mysqli_error($conexion));

if (mysqli_num_rows($registros) > 0) {
    $reg = mysqli_fetch_assoc($registros);
    $return = array('nombre' => $reg['nombre_estudiante']);
} else {
    $return = array('nombre' => 'No existe el registro');
}

header('Content-Type: application/json');
echo json_encode($return);

Greetings, here is the link where it was solved by the user @CodeGodie

link

    
answered by 18.05.2016 / 04:01
source