Data returned in Ajax + PHP request

Asked

Viewed 715 times

3

I have this Ajax that takes the return of a PHP script. For this, I gave an "echo" in php and it returned me the data. If I want to work with more than one data, do I have to create an ajax for each field? For example: I put the badge in a field and with ajax I find the name of the employee in the field and fill in the input just below. But if you wanted to put an admission date on it too, is there a way? Follows AJAX

/**
  * Função para criar um objeto XMLHTTPRequest
  */
 function CriaRequest() {
     try{
         request = new XMLHttpRequest();
     }catch (IEAtual){

         try{
             request = new ActiveXObject("Msxml2.XMLHTTP");
         }catch(IEAntigo){

             try{
                 request = new ActiveXObject("Microsoft.XMLHTTP");
             }catch(falha){
                 request = false;
             }
         }
     }

     if (!request)
         alert("Seu Navegador não suporta Ajax!");
     else
         return request;
 }

 /**
  * Função para enviar os dados
  */
 function getDados() {

     // Declaração de Variáveis
     var nome   = document.getElementById("txtnome").value;
     var result = document.getElementById("content"); //DIV DE RETORNO
     var xmlreq = CriaRequest();

     // Exibe a imagem de progresso
     //result.innerHTML = '<img src="images/Progresso.gif"/>';
     document.getElementById("nomefunc").value = 'Pesquisando...';

     // Iniciar uma requisição
     xmlreq.open("GET", "processa.php?txtnome=" + nome, true);

     // Atribui uma função para ser executada sempre que houver uma mudança de ado
     xmlreq.onreadystatechange = function(){

         // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4)
         if (xmlreq.readyState == 4) {

             // Verifica se o arquivo foi encontrado com sucesso
             if (xmlreq.status == 200) {
                 if (xmlreq.responseText == "") {
                 document.getElementById("nomefunc").value = 'NÃO ENCONTRADO!';
                 }else{
                 document.getElementById("nomefunc").value = xmlreq.responseText; //UNICO CAMPO QUE ABASTECE COM O ECHO DA VARIAVEL
                 }
             }else{
                 result.innerHTML = "Erro: " + xmlreq.statusText;
             }
         }
     };
     xmlreq.send(null);
 }

php code

<?php

include 'config.php';

// Recebe variavel do index
    $cracha = $_GET["txtnome"];

//Inicia a consulta ao banco Oracle, com os dados informados pelo cliente.
$consulta2 = OCIParse($ora_conexao,"select
       CRACHA,
       NOME,
       DIA
FROM PCN_CRACHAS
WHERE CRACHA = '$cracha'
ORDER BY 1");

//aqui prepara a consulta, nome da coluna e a variavel retorno da consulta
OCIDefineByName($consulta2,"CRACHA",$v_cracha);
OCIDefineByName($consulta2,"NOME",$v_nome);
OCIDefineByName($consulta2,"DIA",$v_data);
// executa a consulta
OCIExecute($consulta2);

// Atribui o código HTML para montar uma tabela
 while (OCIFetch($consulta2)){
     echo $v_nome;  //Essa retorna no ajax sem problemas
    // echo $v_data; //Se dou echo nessa, o resultado aparece no mesmo campo, junto com o nome
 }

?>

1 answer

3


When you use the method GET parameters are passed by the URL as you have now:

"processa.php?txtnome=" + nome

the part after the ? is where you have the data. That extra part ?chave=valor is called querystring and you can add more N data separating with &. I mean, if you want to add one more parameter, you can do something like this:

"processa.php?txtnome=" + nome + '&admissao=' + admissao

On the server side

To pass data to the client side you can do so in PHP:

 // Atribui o código HTML para montar uma tabela
 while (OCIFetch($consulta2)){
     $array = array('nome'=>$v_nome, 'data'=>$v_data, 'cracha'=>$v_cracha);
     echo json_encode($array);
 }

and in Javascript you need to parse this JSON so for example:

var dados = JSON.parse(xmlreq.responseText);
alert(dados.nome);
alert(dados.data);
  • I get it. But how do I identify one variable and another in xmlreq.responseText ? Here it returns the value in my input la: Document.getElementById("funct"). value = xmlreq.responseText;

  • @Diego how so? The xmlreq.responseText has what the server sent. what do you get from the server? What is your PHP like?

  • That’s just it. In PHP, I do the query, return 3 variables. For Ajax "catch" the return, I echo one of them. When I echo both of them, the result is right next to each other. Somehow, I would need Ajax to understand that the variable returned from the $name bank goes to such a field and $admission goes to another, in the same div. Anything put an example and pass the access...

  • Put the PHP code in the question I put it together in my answer. In the background you have to make an array in PHP with the variables and do echo json_encode of this variable.

  • I put the code now... thank you!

  • @Diego added more info to the answer.

  • I am trying to apply the return in the fields, but now in the ajax he enters in the "Searching..." and stops. Using the Array you showed, how can I assign the return to the input I want in the index? I did so: var data = JSON.parse(xmlreq.responseText); Document.getElementById("funct"). value = data.name; Document.getElementById("function2"). value = data.data;

Show 3 more comments

Browser other questions tagged

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