Problems with JQuery

1

My app worked correctly, now it does not throw me any kind of error, meanwhile when I run my browser's debugger in sends to jquery caught.

 <!doctype html>
      <html>
      <head>
        <meta charset="utf-8">
    <meta name="viewport" content="width=device-width"/>
    <script src="js/jquery.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="js/jquery-ui.css">
    <script src="js/jquery-ui.js" type="text/javascript"></script>
    <script src="js/jquery.rut.min.js" type="text/javascript"></script>
    <script src="js/validacion.js" type="text/javascript"></script>

    <link href="css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <?php include_once "lib/metodosbd.php";
          include_once "lib/metodos.php";?>
    </head>
    <?php valida_sesion(); ?>

    <script type="text/javascript">

//select dependiente
        $(document).ready(function(){
            $("#region").change(function () {
                        $("#region option:selected").each(function () {
                            id_region = $(this).val();
                            $.post("lib/getComuna.php", { id_region: id_region }, function(data){
                                $("#comuna").html(data);

                            });            
                    });
        });
    });                               
    $(document).ready(function(e) { 
        //valida rut de ingreso
    $("input#rut").rut().on('rutInvalido', function(e) {
           $("#mrut").fadeIn();

    });
      $("input#rut").rut().on('rutValido', function(e, rut, dv) {
        $("#mrut").fadeOut();
    });

     //valida rut buscador

    $("form#buscador input")
      .rut({formatOn: 'keyup', validateOn: 'keyup'})
      .on('rutInvalido', function(){ 
        $("#mrutb").fadeIn();
      })
      .on('rutValido', function(){ 
        $("#mrutb").fadeOut();

      });
      //copia rut en casilla sin digito verificador 
    $("#rutb").change(function () {
            var value = $(this).val();
            $("#rutsf").val(value);
        });
    //rut sin digito verificador
    $("input#rut").rut()
      .on('rutValido', function(e, rut){
        $('#rutsf').val(rut)
      });
      $("#rutb").change(function () {

          $("#rutb").each(function () {
                 $.ajax({
                     type:"GET",
                     url:"busca-cliente.php",
                     data:{busca: $("#rutb").val()},
                     dataType:"json",
                 }).done(function(res){

                        $('#nombre').val(res.nom);
                        $('#rut').val(res.rut);
                        $('#telefono').val(res.tel);
                        $('#direccion').val(res.dir);
                        $('#email').val(res.email);
                        $("#region").val([res.idre,res.desre]);
                        $("#comuna").val([res.idco,res.desco]);
                        document.getElementById("rut").focus();
                        if(res.mensaje == 1){
                            //no existe el cliente
                            $("#mensaje").text("El cliente no existe en la base de datos.");
                            $("#mensaje").css("display", "inline");
                            $("#btn-insert").css("display", "inline");
                            $("#btn-updete").css("display", "none");
                        }else{
                            //el cliente existe, puede actualizar
                            $("#mensaje").css("display", "none");
                            $("#btn-insert").css("display", "none");
                            $("#btn-updete").css("display", "inline");
                        }
                    });
          });
      })




    });

    </script>
    <body>
    <header>
    <div class="div-header">
      <section class="main row">
        <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1"> <img src="img/OXblanco.png" width="320" height="107" ></div>
        <div class="col-xs-6 col-sm-9 col-md-9 col-lg-9"></div>
        <div class="col-xs-5 col-sm-2 col-md-2 col-lg-2 nom-usuario"><?php echo $_SESSION['nombre_per']; ?></div>
      </section>
    </div>
    <div class="container">
      <h2 style="margin-top:10px; margin-bottom:20px;">Ingresar Clientes</h2>

      <section class="main row" >
        <div class=" col-lg-12">

           <form  method="get" id="buscador" class="form-horizontal style-form">
           <span style="margin-left:18px; margin-top:15px;" class="help-block">Utilice esta casilla para buscar al cliente, si el cliente existe los campos se completarán automáticamente, de lo contrario es necesario ingresarlo.</span>
            <div class="form-group">
              <label class="col-sm-4" for="rutb" style="margin-top:1%;">Buscar cliente</label>
              <div class="col-sm-8">

              <input name="rutb"  style="margin-top:5px;" type="text"  id="rutb"  class="form-control" />

              </div>
            </div>
           <span id="mensaje" class="alert-advertencia" ></span>
           <div class="alert-rutb" id="mrutb">El rut no es valido</div>
         </form>

        </div>
                    <div class="col-lg-12">
                            <form method="post" id="ingresar" class="form-horizontal style-form" onSubmit="return Comprobar();">
                            <div class="form-group">
                                  <label class="col-sm-3  control-label" for="rut">Rut :</label>
                                  <div class="col-sm-3">
                                      <input id="rut" name="rut" type="text" class="form-control">
                                        <div class="errores-iz" id="mrut">El rut no es valido</div>
                                  </div>
                                  <label for="nombre" class="col-sm-3  control-label">Nombre :</label>
                                  <div class="col-sm-3">
                                      <input id="nombre" name="nombre" type="text" class="form-control">
                                     <div id="mnom" class="errores-de">El nombre no es valido</div>
                                  </div>
                              </div>
                              <div class="form-group">
                                  <label class="col-sm-3 control-label" for="region">Región :</label>
                                  <div class="col-sm-3">
                                      <select class="form-control" id="region"  name="region">
                                        <option  value="0">Seleccione</option>
                                        <?php get_region();?>
                                      </select>
                                       <div class="errores-de" id="mregion">Seleccione una region.</div>
                                  </div>
                                 <label class="col-sm-3 control-label" for="comuna">Comuna :</label>
                                  <div class="col-sm-3">
                                      <select class="form-control" name="comuna" id="comuna" >
                                      <option value="0">Seleccione</option>
                                      <?php get_comuna();?>
                                      </select>
                                      <div class="errores-de" id="mcomuna">Seleccione una comuna.</div>
                                  </div>
                               </div>
                              <div class="form-group">
                                  <label for="telefono" class="col-sm-3 control-label">Teléfono :</label>
                                  <div class="col-sm-3">
                                      <input id="telefono" name="telefono" type="text" class="form-control">
                                    <div class="errores-iz" id="mtel">El teléfono no es valido </div>
                                    <div class="errores-iz" id="mtel2">El número de telefono debe tener 9 digitos </div>
                                  </div>
                                  <label for="direccion" class="col-sm-3 control-label">Dirección :</label>
                                  <div class="col-sm-3">
                                      <input id="direccion" required name="direccion" type="text" class="form-control">
                                  </div>
                            </div>
                             <div class="form-group">
                                 <div class="col-sm-1"></div>
                                  <label for="email"   class="col-sm-4 control-label">Email :</label>
                                  <div class="errores-iz" id="memail">Debe ingresar el email</div>
                                  <div class="col-sm-6">
                                      <input id="email" name="email" type="email"  required class="form-control">
                                  </div>
                                 <div class="col-sm-1"></div>
                                <input name="rutsf" type="hidden"  id="rutsf" />
                             </div>

                            <div class="form-group">

                             <button type="submit" name="insertar"  class="button" id="btn-insert">Insertar</button>
                             <button type="submit" name="actualiza"  style="display:none;" class="button" id="btn-updete">Actualizar</button>
                            </div>

                            </form>
                </div>



    </div>

The app sends the rout to the page search-client.php and it returns an array of typo json, but I suspect that it is the data that is not sent. Run search-client.php and return the data .

<?php
include_once "lib/conexion.php";
$rutbuscador=$_GET['busca'];
  if(!empty($rutbuscador)){
    $con=conectar();

     $sqls = "SELECT * FROM clientes WHERE     (RutAux = '$rutbuscador')"; 

$query= sqlsrv_query($con,$sqls);

if(sqlsrv_has_rows($query)){
        for($f = 1; $f <=1 ;$f++){
            $fila=sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC);

            $NOM=$fila['NomAux'];
            $RUT=$fila['RutAux'];
            $DIR=$fila['DirAux'];
            $FON=$fila['FonAux1'];
            $EM=$fila['EMail'];
            $REGID=$fila['Region'];$REGDES=$fila['Descripcion'];

            $COMDES=$fila['ComDes'];$COMID=$fila['ComAux'];
            $clientes= array("rut" =>$RUT, "nom" => $NOM,"tel" => $FON,"dir" => $DIR,
                             "email" => $EM,"idre" => $REGID,"desre" => $REGDES,
                             "idco" => $COMID,"desco" => $COMDES,"mensaje"=> 0);

            }
        echo json_encode($clientes);

    }else{
        $clientes= array("rut" =>$rutbuscador,"nom" => "","tel" => "","dir" => "","email" => "","mensaje"=> 1,"idre" => 0,"idco" => 0);
        echo json_encode($clientes);
    }
}

? >

PS: Rout validation and nested select work correctly.

    
asked by Johann Sebastian Painevil Len 20.11.2018 в 19:22
source

4 answers

3

1- As a first suggestion, I think you should put your Javascript code at the end of the body, this way the page and its elements are loaded ...

Sometimes it fails when you put it up.

2- Check that your json is not receiving accents, apostrophes, etc. to ensure encode non-numeric fields with utf8_encode or by doing echo json_encode ($ clients, JSON_UNESCAPED_UNICODE) ;

3- To verify that the request is executed to the search-client.php, press F12 in chrome and go to network choose only XHR, and see that this file is listed, click on it and look in the tab Headers-> formData . There you have all the details of the petition.

    
answered by 20.11.2018 / 21:02
source
0

Thanks to point 3 I was able to capture an error which is: Warning: sqlsrv_has_rows () expects parameter 1 to be resource, boolean given in C: \ xampp \ htdocs \ clientsv2 \ search-client.php on line 11

Check the query and I noticed that they modified it, with the correct query, but it still does not work again I tried adding an error to the attributes of ajax and it prints the arlet, how can I concatenate the error?

 $.ajax({
             type:"GET",
             url:"busca-cliente.php",
             data:{busca: $("#rutb").val()},
             dataType:"json",
             error: function(){
             alert("error");
             }

         }).done(function(res){
                $('#nombre').val(res.nom);
                $('#rut').val(res.rut);
                $('#telefono').val(res.tel);
                $('#direccion').val(res.dir);
                $('#email').val(res.email);
                $("#region").val([res.idre,res.desre]);
                $("#comuna").val([res.idco,res.desco]);
                if(res.mensaje == 1){
                    //no existe el cliente
                    $("#mensaje").text("El cliente no existe en la base de datos.");
                    $("#mensaje").css("display", "inline");
                    $("#btn-insert").css("display", "inline");
                    $("#btn-updete").css("display", "none");
                }else{
                    //el cliente existe, puede actualizar
                    $("#mensaje").css("display", "none");
                    $("#btn-insert").css("display", "none");
                    $("#btn-updete").css("display", "inline");
                }
            });
    
answered by 21.11.2018 в 13:37
0

$. ajax ({              type: "GET",              url: "search-client.php",              data: {search: $ ("# rutb"). val ()},              dataType: "json",              error: function () {               alert ("error"); // This alert will always print it because it is not as an event, but as an attribute - > Investigate about the onError              }

1- You can trace the process step by step from the Source tab of the Inspector, and see that the thing goes as you want.

2- In network, check if the JSON returns the call that you are expecting or returns an error. You can make a console.log (res); to see if it prints the result of the post in the Inspector's Console.

    
answered by 21.11.2018 в 16:03
0

SOLVED! The error is simple the app stopped working when you un-comment the print_r: connect, well if I comment this line the application works function connect () {

        $server="localhots";
        $bd="clientes";
        $pass="";
        $coninfo= array("Database"=>$bd,"UID"=>"sa","PWD"=>$pass,"CharacterSet"=>"UTF-8");
        $con = sqlsrv_connect($server, $coninfo);

            if($con){
                //print_r("conectado a: ".$bd);
            }else{
                ?>
                <div class="alert-false" role="alert">Error: <?php die(print_r(sqlsrv_errors(),true));?></div> 
                <?php
            }
            return $con;

}

    
answered by 21.11.2018 в 16:04