Working with Ajax

Asked

Viewed 48 times

0

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

The code below works, but it only brings messaging if the customer is registered and separated if he is not registered. But beyond that, I want to fill out the combos with his data, vehicle color, model, brand automatically too.

I tried with Session, but in html it only appears if I leave and go back to page.

//fill the customer type after the card 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";
    }

?>

2 answers

2

First step is the addition of dataType:"Json" in his $.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 awaits a Json as return, so let’s set for the PHP an answer in Json, instead of a string common as in the current return, using the function 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()

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

  • Assuming your query brings the following database results:

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

The parameter data of the return function of the 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 out the fomeular according to your need.

But if it is a single user, then instead of this array, another 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() see dataType

  • I made a modification : $Rows = mysqli_fetch_assoc($result) - To have an array. When I print the date, it shows me the array. When I print the date.idmensalista, for example, it comes: Undefined. In its original form, it didn’t work :(

  • But data["idmensalista"] worked?

  • It did not work, I will test other ways. It comes Undefined too

  • @Joãopaulosilva Put one console.log(data) in the complete and post here what is showing.

0

I managed to solve 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"});     


        }



    });     

Browser other questions tagged

You are not signed in. Login or sign up in order to post.