Get php return in Ajax

Asked

Viewed 298 times

-2

I need to take the value of an ajax, after a php fetchAll

I am doing a function to calculate the freight of a commodity based on a database of deliveries that I own, already with a predefined value.

How to take this return from ajax?

So I make a request via ajax

//funcao ajax
$("#txtCepFrete").on('focusout',function () {
    var cep = $("#txtCepFrete").val();
    $.ajax('classes/getCEP.php',   // request url
     {
          data:{cep:cep},
           success: function (data, status, xhr) {// success callback function
                console.log(data);
          }
    });
 });

getCep.php

require_once ("CEP.php");
$CEP = new CEP();

if(isset($_GET['cep'])){
    $cep = $_GET['cep'];
    if( $cep != ''){
        if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {


            $CEP->setCepAtendiddo($cep);
            $retorno = $CEP->buscarCEPDisponivel();
            if(empty($retorno->nome_bairro)){
                print_r($retorno);
            }else{
                print_r('Não encontrou');
            }


        }else if(empty($cep)){

            $CEP->setCepAtendiddo($cep);
            $retorno = $CEP->buscarCEPDisponivel();
            if(empty($retorno->nome_bairro)){
                printf($retorno);
            }else{
                print_r('Não encontrou');
            }
        }
        else{

            $CEP->setCepAtendiddo($cep);
            $retorno = $CEP->buscarCEPDisponivel();
            if(empty($retorno)){
                printf($retorno);
            }else{
                print_r('Não encontrou');
            }
        }

    }

}

php function that makes Calulo and the return is received back by ajax

 public function buscarCEPDisponivel()
    {
        try{

            $sql = "SELECT * FROM `bairros_entregues` WHERE cep_atendido = :cep";
            $stmt = DB::prepare($sql);
            $stmt->bindParam(":cep",$this->cep,PDO::PARAM_INT);
            $stmt->execute();
            return $stmt->fetchAll();
        }catch (PDOException $ex){
            echo $ex->getMessage();
            $Exc = new ExceptionDatabase();
            $this->arquivo = $this->Caminho[count($this->Caminho)-1];
            $this->arquivoLog = 'log/erros.txt';
            $this->erro =  $ex->getCode();
            $this->mensagem  = $ex->getMessage();

            $Exc->setArquivo($this->arquivo);
            $Exc->setArquivoLog($this->arquivoLog);
            $Exc->setErro($this->erro);
            $Exc->setMensagem($this->mensagem);

            $Exc->erro();
        }
    }

The return

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [nome_bairro] => Al�pio de Melo
            [cep_atendido] => 30820600
            [frete_bairro] => 3.5
        )

)

1 answer

0

First your request is ajax needs to inform the method that the PHP wait. in this case it is necessary to use the method GET, so I believe that script would look this way:

//funcao ajax
$("#txtCepFrete").on('focusout',function () {
    var cep = $("#txtCepFrete").val();
    $.get(`classes/getCEP.php?cep=${cep}`, function (data, status, xhr) {
        console.log(data);
    }, 'JSON');
 });

Following the documentation of jQuery this function $.get can define the return that awaits the PHP, one JSON normalmnente.

https://api.jquery.com/jquery.get/

However you must use the function json_encode instead of print_r in the code getCep.php:

require_once ("CEP.php");
$CEP = new CEP();

if(isset($_GET['cep'])){
    $cep = $_GET['cep'];
    if( $cep != ''){
        if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {


            $CEP->setCepAtendiddo($cep);
            $retorno = $CEP->buscarCEPDisponivel();
            if(empty($retorno->nome_bairro)){
                print(json_encode($retorno[0]));
            }else{
                print_r('Não encontrou');
            }


        }else if(empty($cep)){

            $CEP->setCepAtendiddo($cep);
            $retorno = $CEP->buscarCEPDisponivel();
            if(empty($retorno->nome_bairro)){
                printf($retorno);
            }else{
                print_r('Não encontrou');
            }
        }
        else{

            $CEP->setCepAtendiddo($cep);
            $retorno = $CEP->buscarCEPDisponivel();
            if(empty($retorno)){
                printf($retorno);
            }else{
                print_r('Não encontrou');
            }
        }

    }

}

Good luck!

  • opa, boa, valeu vou testar

  • Old, @Kleber Olivera, his return comes empty

Browser other questions tagged

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