Call php function using onblur (completed)

Asked

Viewed 854 times

0

I have an event onblur to call a function and this function has to call a php class in order to compare what was typed in the input with what is in my BD, but I don’t know how to do it using jquery, how do this?

HTML

<html>
<head>
<title>Validação de campos com AJAX</title>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script type="text/javascript" src="assets/ajax/check_cnae.js"></script>
</head>
<body>

Login: <br /> <input type="text" id="cnae" onblur="validarDados('cnae', document.getElementById('cnae').value);" />
<div id="campo_cnae"> </div>

</body>
</html>

class

require_once "Conexao.class.php";

class Socio {    
  private $con;
  private $cnae; 

public function __construct(){
    $this->con = new Conexao();
}

public function __set($atributo, $valor){
    $this->$atributo = $valor;
}

public function __get($atributo){
    return $this->$atributo;
}

public function cnae(){
    $this->cnae = $_GET['valor'];
        $validar = $this->con->conectar()->prepare("SELECT cnae FROM cnae WHERE cnae = ?");
        $validar->execute(array($this->cnae));   
        if($validar->rowCount() == 0){
            echo "CNAE invalido.";
        }else{
            echo "CNAE valido.";
        }
}

script

var req;

function validarDados(campo, valor) {

// Verificar o Browser
// Firefox, Google Chrome, Safari e outros
if(window.XMLHttpRequest) {
   req = new XMLHttpRequest();
}
// Internet Explorer
else if(window.ActiveXObject) {
   req = new ActiveXObject("Microsoft.XMLHTTP");
}

// Aqui vai o valor e o nome do campo que pediu a requisição.
var url = "../../index_teste2.php?campo="+campo+"&valor="+valor;

// Chamada do método open para processar a requisição
req.open("Get", url, true);

// Quando o objeto recebe o retorno, chamamos a seguinte função;
req.onreadystatechange = function() {

// Exibe a mensagem "Verificando" enquanto carrega
if(req.readyState == 1) {
    document.getElementById('campo_' + campo + '').innerHTML = '<font color="gray">Verificando...</font>';
}

// Verifica se o Ajax realizou todas as operações corretamente (essencial)
if(req.readyState == 4 && req.status == 200) {
// Resposta retornada pelo validacao.php
var resposta = req.responseText;

// Abaixo colocamos a resposta na div do campo que fez a requisição
document.getElementById('campo_'+ campo +'').innerHTML = resposta;
}
}
req.send(null);
}

PHP file that receives instantiation

require_once 'classes/Socio.class.php';

$socio = new Socio();

if(isset($_GET['valor'])){
    $dados = $socio->cnae($_GET['valor']);
}
  • 1

    You need to do, in function validarDados(), an Ajax call for some PHP file and this file should do the checking, then just return some result with PHP and handle in Javascript.

  • It’s just this part that I don’t know @Gabrielqueirozschicora, I’m watching some videos on youtube to see if it helps.

  • 1

    I put an example in the answers

  • @Gabrielqueirozschicora I even put a script in ajax, but I can’t access mine Function cnae, I’ll edit and put the script I tried.

  • 1

    You’re sending a requisition to your class(Socio.class.php), but when it gets there, nothing happens, because nowhere is being called its function cnae, she’s just being raised, so you’d have to call her somewhere cnae(); or, as would be the most correct in my opinion, create a separate file that will instantiate your class and call the cnae function, as is exemplified in my reply, after all send an ajax request to a class I think it is not a good practice.

  • @Gabrielqueirozschicora, I managed to get the result I wanted, but there’s only one problem, the return is duplicating my input and I couldn’t find the error, [link]http://www.acivg.com/index_teste.php, I edited the code to see how it looked, I didn’t use your example but opened the mind.

  • @Gabrielqueirozschicora, thanks for the tip, I managed to get the result and solved the problem of duplication of input, was instantiating in the same php file that received the answer, I had to separate and do in 4 files, now working the way I want.

  • 1

    I’m glad you solved, we need to be there.

Show 3 more comments

1 answer

1


Basically an Ajax function works with this structure (I’m putting an example, you need to adapt to your use).

This script will make a request for the file verificaDado.php using the method GET. It is also explicit that will be passed data of the type json and returned of the type html, I’m assuming you return only one true or false, if you return something more complex (an array for example) you need to change to dataType: 'json' and in php change to echo json_encode($seuArray).

Follow the example codes:

<script type="text/javascript">
    //Essa variável recebe o valor do input
    var inputVal = $('input').val();

    $.ajax({
      type: "get",
      url: "verificaDado.php",
      data: { value: inputVal },
      dataType: 'html',
      contentType: "json"
  }).done(function(obj) {
    //Caso de tudo certo com o ajax vai cair aqui e a variavel obj é o retorno
  }).fail(function(){
    //Caso ocorra alguma falha no ajax cai aqui
  });

</script>

In PHP:

 $socio = new Socio();

 //O echo funciona como o retorno para o ajax, então o que for mostrado na tela vai voltar para o Ajax
 echo $socio->funcao_para_verificar($_GET['value']);

Browser other questions tagged

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