Help, make consultation with ajax, json, php

1

Greetings friends, I am currently solving an exercise in which I want to make a query without having to reload the page, for this reason I am using ajax ... But I have been several hours and nothing that I have with the solution, e watched some examples that exist on the internet but not even that and managed to solve it.

The problem is that the browser does not give me any error, but it hangs on executing the query and I must close the tab to return it to normal.

What I want to do is insert a cedula number and when clicking on a button, check if it exists in my database, if it exists, you should bring me some values that will be assigned in several text boxes

This is the code that I have in the head of the page

<script type="text/javascript" src="../js/jquery-2.2.4.js"></script>
    <script type="text/javascript">

        $(document).ready(function(){

            // Asigno un evento a un botón de mi formulario

            $("[name='buscar_cli']").click(function(e){

                e.preventDefault();

                var datos_enviados = {
                    'buscar_cli' : $("[name='ced_cli']")
                }

                $.ajax({
                    type:'POST',
                    url: 'bd_comun.php',
                    data: datos_enviados,
                    datatype: 'json',
                })

                // Compruebo si me esta trayendo los valores

                .done(function(data){

                    console.log(data);
                    var datos2 = JSON.parse(data);
                    console.log(datos2);

                })

            })

        })

    </script>

I send the form to a php script

if(isset($_POST['buscar_cli'])){

$persona = new usuario();
    $valor = $persona->buscarCliente($_POST['buscar_cli']);
}

Finally sent the data to another php script to make the query

public function buscarCliente($ced){

    $buscar = "SELECT COUNT(*) FROM registro_clientes WHERE rc_cedu=:a";
    $resultado = $this->db_conexion->prepare($buscar);
    $resultado->execute(array(':a'=>$ced));

    $filas = $resultado->fetchColumn();

    if($filas>0){

        $extraer = "SELECT rc_cedu,rc_nomb,rc_aped,rc_telf,rc_dire FROM registro_clientes WHERE rc_cedu=:a";
        $resultado2 = $this->db_conexion->prepare($extraer);
        $resultado2->execute(array(':a'=>$ced));

        $data["datos"][] = $resultado2->fech(PDO::FETCH_ASSOC);

        echo json_encode($data);
        $resultado2->closeCursor();
    }else{
        echo 'Error';
    }

    $resultado->closeCursor();
    $this->db_conexion = null;
}

That's what I have friends, I comment that my experience with ajax is null. If you can help me, I would appreciate it, I have already modified the exercise several times but I can not make it work: (

    
asked by Kevin Melendez 16.11.2017 в 11:13
source

1 answer

0

Try this way. I have applied some things said in comment.

jQuery

  • I have used updated jQuery code (document.ready is obsolete).
  • I have added fail .
  • If you answer properly on the server, you do not need to pause the JSON afterwards.

    $(function() {
    
        // Asigno un evento a un botón de mi formulario
    
        $("[name='buscar_cli']").click(function(e){
    
            e.preventDefault();
    
            var datos_enviados = {
                'buscar_cli' : $("[name='ced_cli']")
            }
    
    
        var request = $.ajax({
          url: "bd_comun.php",
          method: "POST",
          data: datos_enviados,
          dataType: "json"
        });
    
    
        request.done(function( data ) {
            alert("Todo bien");
            console.log(data); //Si pones el content-type en PHP no necesitas parse         
        });
    
        request.fail(function( jqXHR, textStatus ) {
          alert( "Hubo un error: " + textStatus );
        });
    
    
        })
    
    });
    

PHP

  • The code has some problems. Among them that is not consistent. If Ajax expects a json, which is what you indicated in dataType , it is not good practice to make a simple echo if there is an error. You must collect the result of the code in a variable and print it at the end as json, because that is what Ajax expects.
  • In PDO you have to use fetchAll and not fetch if you want all the results in an array, all at once. fetch is to go iterating in a loop . Ignore this. The comment of @aldanux has made me see that with fetch you can in effect store a complete row in an array of results. If it was more than one row (and there are not many rows), you can then use fetchAll .
  • I do not see much logic in the use of two queries, first one to count and then another to obtain the data. I think it could be done with just one, but that is up to you.

I hope it serves you.

public function buscarCliente($ced){

    $buscar = "SELECT COUNT(*) FROM registro_clientes WHERE rc_cedu=:a";
    $resultado = $this->db_conexion->prepare($buscar);
    $resultado->execute(array(':a'=>$ced));

    $filas = $resultado->fetchColumn();

    if($filas>0){

        $extraer = "SELECT rc_cedu,rc_nomb,rc_aped,rc_telf,rc_dire FROM registro_clientes WHERE rc_cedu=:a";
        $resultado2 = $this->db_conexion->prepare($extraer);
        $resultado2->execute(array(':a'=>$ced));

        $arrResultado["datos"][] = $resultado2->fetch(PDO::FETCH_ASSOC);

        $resultado2->closeCursor();
    }else{
        $arrResultado=array("error"=>"No se encontraron datos");
    }

    $resultado->closeCursor();
    $this->db_conexion = null;

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

 }
    
answered by 16.11.2017 / 13:13
source