Search via POST by clicking on div

Asked

Viewed 36 times

0

I am adapting the following script:

$(document).ready(function(){
    $('#getUser').on('click',function(){
        var user_id = $('#user_id').val();
        $.ajax({
            type:'POST',
            url:'php/getData.php',
            dataType: "json",
            data:{user_id:user_id},
            success:function(data){
                if(data.status == 'ok'){
                    $('#userName').text(data.result.name);
                    $('#userEmail').text(data.result.email);
                    $('#userPhone').text(data.result.phone);
                    $('#userCreated').text(data.result.created);
                }else{
                    alert("User not found...");
                } 
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user_id" />
<input type="button" id="getUser" value="Get Details"/>
<div class="user-content">
    <h4>User Details</h4>
    <p>Name: <span id="userName"></span></p>
    <p>Email: <span id="userEmail"></span></p>
    <p>Phone: <span id="userPhone"></span></p>
    <p>Register Date: <span id="userCreated"></span></p>
</div>

<?php
if(!empty($_POST['user_id'])){
    $data = array();
	
	/******* Conexão com o bando de dados *******/			
	include "../../Conexao/config.php";
					
	mysqli_select_db($config, $database_config);
	mysqli_set_charset($config,"utf8");
	/******* Conexão com o bando de dados *******/		
    
    //database details
    $dbHost     = $hostname_config;
    $dbUsername = $username_config;
    $dbPassword = $password_config;
    $dbName     = $database_config;
    
    //create connection and select DB
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    if($db->connect_error){
        die("Unable to connect database: " . $db->connect_error);
    }
    
    //get user data from the database
    $query = $db->query("SELECT * FROM users WHERE id = {$_POST['user_id']}");
    
    if($query->num_rows > 0){
        $userData = $query->fetch_assoc();
        $data['status'] = 'ok';
        $data['result'] = $userData;
    }else{
        $data['status'] = 'err';
        $data['result'] = '';
    }
    
    //returns data as JSON format
    echo json_encode($data);
}
?>

It works with the "click" event. I need it to work with the keyboard TAB or when clicking on the div, as in this cep query:

https://viacep.com.br/exemplo/jquery/

1 answer

1


This effect is achieved with the event blur which occurs when losing focus of the text field.

It would be something like:

$('#user_id').on('blur', function () {
  ...
});

More information

Blur (event)

Browser other questions tagged

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