questions

Getting response back from server but .html not sowing anything in wordpress ajax

Rate this post

On click I’m sending the id as data and then using query showing the name of user from WordPress database. I’m getting the response back from server but It is not adding when try to use .html(response).May be this is something to do with permission ?Like only admin can use the response? If that’s the case what I can do.

This is the ajax function:

    function get_user_id() {
    let get_current_user_id =jQuery(this).attr('id');
    cur_user = '<?php echo get_current_user_id() ;?>';
    var postdata_name = {action: "incoming_user_name_ajax_call",
    param_user_to_chat: get_current_user_id,};

    jQuery.post(ajaxurl, postdata_name, function (response) {
    jQuery("#name-incoming-user").html(response);});

}

This is the function in functions.php

  add_action("wp_ajax_incoming_user_name_ajax_call", "incoming_user_name_ajax_call_fn");
  add_action("wp_ajax_nopriv_incoming_user_name_ajax_call", "incoming_user_name_ajax_call_fn");


   function incoming_user_name_ajax_call_fn() {
   global $wpdb;
   $param_user_to_chat=isset($_REQUEST['param_user_to_chat'])?trim($_REQUEST['param_user_to_chat']):"";

   if (!empty($param_user_to_chat)) {

   $posts = $wpdb->get_results("SELECT distinct(display_name) FROM wp_users where  
   ID=$param_user_to_chat");
   echo $posts[0]->display_name;

  }
  wp_die();}

Posting the HTML as well for everyone who want to know what jQuery(this).attr(‘id’); is doing. It is getting id “4” or “2” depending on click.

<div id="target">
  <div class="user-list-hide" id="user-hide" style="display: block;">
   <div id="4"><span>Jason Bradley</span>/div>
   <div id="2"><span>John Saddington</span></div>
  </div>
</div>

 

✔️Solution:

There was issue in your jquery code i.e : the way you were calling your get_user_id() function here you have use wrong selector to get your inner divs . So, to make it work change :

jQuery("#target").on("click", "div", get_user_id); 

to

jQuery("#user-hide").on("click", "div", get_user_id);

Leave a Reply

Your email address will not be published.

Back to top button