Working with Ajax

0

In the blur event of a field, I give a select in my bank and bring a value and fill in my html. My question is how do I get more than one result or a specific result in the ajax date.

The code below works, but it only brings monthly if the customer is registered and free if he is not registered. But in addition, I want to fill in the combos with his data, the color of vehicle, model, brand automatically as well.

I tried with session, but in html it only appears if I go out and come back on the page.

// fill in client type after board is typed - input screen

$("#txtplaca").blur(function() {
    var url = 'consulta_tip_cli.php';
    var txtplaca = $("#txtplaca").val();    
    $.ajax ({
        url: url,
        data: {'txtplaca': txtplaca},
        method: 'POST',
        success: function(data) {

            var msg = data;
            $("#tipo").val(msg);
        },      
        beforeSend: function(){
            $("#loader").css({display:"block"});
        },      
        complete: function(){
            $("#loader").css({display:"none"});
        }   
    });
});

My php:

<?php
    include_once('status_logado.php');

    require_once('db.class.php');

    $placa = $_POST['txtplaca'];


    $sql = "SELECT idmensalista FROM 'tbl_mensalista' join tbl_veiculo on IDMENSALISTA = id_mensalista ";
    $sql = $sql."where vei_placa = '$placa'";

    $objDb = new db();
    $link = $objDb->conecta_mysql();

    $resultado = mysqli_query($link,$sql);
    $rows = mysqli_num_rows($resultado);

    if($rows) {
        echo "Mensalista";
    } else  {
        echo "Avulso";
    }

?>
    
asked by anonymous 29.07.2018 / 14:37

2 answers

2

First step is to add dataType:"Json" to your $.Ajax() :

$("#txtplaca").blur(function() {
    var url = 'consulta_tip_cli.php';
    var txtplaca = $("#txtplaca").val();    
    $.ajax ({
        url: url,
        data: {'txtplaca': txtplaca},
        method: 'POST',
        dataType:"Json",
        success: function(data) {
            //aqui serão recebidos os dados em json da resposta do php
        },      
        beforeSend: function(){
            $("#loader").css({display:"block"});
        },      
        complete: function(){
            $("#loader").css({display:"none"});
        }   
    });
});

Now you have an event that expects a Json as a return, so let's set PHP to a response in Json , instead of a string common as in the current return, using the json_encode() :

include_once('status_logado.php');
require_once('db.class.php');
$placa = $_POST['txtplaca'];

$sql = "SELECT idmensalista FROM 'tbl_mensalista' join tbl_veiculo on IDMENSALISTA = id_mensalista ";
$sql = $sql."where vei_placa = '$placa'";
$objDb = new db();
$link = $objDb->conecta_mysql();

$resultado = mysqli_query($link,$sql);
$rows = mysqli_num_rows($resultado);

if($rows) {
    echo json_encode($resultado);
} else  {
    echo json_encode(array("error"=>"Avulso"));
}

$. Ajax ()

Inside the parameter success of $.Ajax() we are now receiving an associative array as a response, containing all information that was found by the mysqli_query function or an error message, containing "Avulso" value.

  • Assuming your query brings the following results from the database:

    array (     "plate" = > "abcd-1234",     "owner" = > "So-and-so",     "parents" = > "Brazil" )

The data parameter of the return function of success now contains this array as content, being extracted like this:

alert(data.placa)
//"abcd-1234"

alert(data["proprietario"])
//"Funlado de Tal"

Now you have access to the information and can fill in the fomeulário according to your need.

But if it is a single user, then instead of this array, another one will come, with an error key, and can be treated like this:

success: function(data) {
    if(data.error){
        var msg = data.error;
        $("#tipo").val(msg);
    }else{
        //aqui vai ser definido os alocamentos dos dados caso a função traga os resultados do banco de dados
    }
},
  

Reference - json_encode ()

     

Reference - $. Ajax () view dataType

    
29.07.2018 / 16:32
0

I solved the problem! the tips helped me get on a path and adapt, thank you!

include_once('status_logado.php');
require_once('db.class.php');

//crio uma array
$retorno = array();

$placa = $_POST['txtplaca'];

//populo
$retorno['placa'] = $placa;
echo(json_encode($retorno));
die();

$.ajax ({
        url: url,
        data: {'txtplaca': txtplaca},
        method: 'POST',
        dataType: 'json',
        success: function(data) {

            var result = data.placa; -- acesso a posicao do array       
                alert(result); 
        },
        error: function(ex) {
            console.log(ex);
        },

        beforeSend: function(){
            $("#loader").css({display:"block"});
        },

        complete: function(){
            $("#loader").css({display:"none"});     


        }



    });     
    
03.08.2018 / 19:50