How to change the value of a variable using input field?

I have created a wordpress website. I want to extract each user's data using php through his/her id.

I have created this code;

?php
$userid = /* help me get the below input field's value */
$user_info = get_userdata($userId);
      echo 'Username: ' . $user_info-user_login . "\n";
      echo 'User roles: ' . implode(', ', $user_info-roles) . "\n";
      echo 'User ID: ' . $user_info-ID . "\n";
    ?
input name="getUser" id="getUser" value=''/

The user will write the id of the user he wants to extract his data. and then the data will echo back.

The code is working fine but i can't set the value of "getUser" input field to "$userId" variable. Also i want that php to re-execute on input field value change.

Topic user-meta variables php users Wordpress

Category Web


Please try below snippet of code.

HTML :

<input name="getUser" id="getUser" value=''/>
<div id="user_data"></div>

JS (js/my-ajax-script.js)

 jQuery(document).ready(function($){
    $('#getUser').keyup(function(e) {
      var user_id = e.target.value;
      console.log(user_id);
      $.ajax({
            url:my_ajax_object.ajaxurl, #add here your ajax url
            type:'POST',
             data:'action=get_this_user_data&user_id='+user_id ,
             success:function(results)
             {
              jQuery('#user_data').html(results);

             }
        });
    });
});

Ajax (add in functions.php)

function my_enqueue() {

wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );

wp_localize_script( 'ajax-script', 'my_ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
   }
   add_action( 'wp_enqueue_scripts', 'my_enqueue' );

add_action( 'wp_ajax_get_this_user_data', 'get_this_user_data' );
add_filter( 'wp_ajax_nopriv_get_this_user_data', 'get_this_user_data');
function get_this_user_data()
{
    $userid = $_POST["user_id"];
    $data = '';
    $user_info = get_userdata($userid);
     if(!empty($user_info))
     {
       $data .= '<pre>';
       $data .= 'Username: ' . $user_info->user_login . '<br/>';
       $data .= 'User roles: ' . implode(', ', $user_info->roles) . '<br/>';
       $data .= 'User ID: ' . $user_info->ID . '<br/>';
       $data .='</pre>';
     }
     else
     {
        $data = "user data not found";
     }

      echo $data;
      die();
}

Hope this helps you!

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.