how to recover json php data with ajax

Asked

Viewed 526 times

0

how can I recover data coming from a php with the ajax. because I’m getting the result but it’s not coming to the jquery he doesn’t bring me values

query code

if(isset($_POST['cep'])){
    $cep = $_POST['cep'];
    $newCep = str_replace("-", "", $cep);

    require_once "../Model/Correios.class.php";

    $p = new Correios("15991182","{$newCep}","0.300","5","11","11","0","04510");
    $s = new Correios("15991182","{$newCep}","0.300","5","11","11","0","04014");

    $pac = $p->getValor();
    $prazoPac = $p->getPrazoEntrega();

    $sedex = $s->getValor();
    $prazoSedex = $s->getPrazoEntrega();

    $retorno = array("pac"=>$pac, "prazoP"=>$prazoPac, "sedex"=>$sedex, "prazoS"=>$prazoSedex);

    echo json_encode($retorno);
  }else{
    header("location:../");
  }

ajax code

$.ajax({
                  url: 'Controller/consultaCep.php',
                  type: 'POST',
                  data: dado,

                  success: function(r){
                    valorP = r.pac;
                    valorS = r.sedex;
                    prazoP = r.prazoP;
                    prazoS = r.prazoS;

                    alert(valorP);

                  $("#pacCorreio").val(valorP);
                  $("#pacCorreio").html("PAC - "+prazoP+" dias após postagem R$ "+valorP);
                  $("#sedexCorreio").val(valorS);
                  $("#sedexCorreio").html("Sedex - "+prazoS+" dias após postagem R$ "+valorS);
                  $("#todo").show();
                  }
                })

              });
  • To callback success is being executed at least? The problem is not clear.

  • yes it is running all only it is not getting the php values in alert(valorP) you’re returning to me undefined

  • I executed the console.log and he shows me the values of echo json_encode($retorno);

  • In the $.ajax, place dataType: 'json' to inform jQuery that the return will be JSON. See if anything changes.

  • managed to resolve. have to convert again this json of php for js with the JSON.parse converted and function he brought me the results

No answers

Browser other questions tagged

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