Thanks JimL
PHP is used to query the database and the js is only used to hide and show the divs.
function gedshow_get_name_function(){
global $wpdb;
$facts_tbl = $wpdb->prefix.'gedshow_facts';
$name_tbl = $wpdb->prefix.'gedshow_names';
//My code starts here
//Get surnames from Names table
$name = sanitize_text_field($_GET['sname']);
$query = "
SELECT *
FROM $name_tbl
WHERE surname LIKE '$name'
ORDER BY given ASC";
$results = $wpdb->get_results($query, OBJECT);
ob_start();
?>
<div class="cs_section"> <h5><?php echo (strtoupper($name));?></h5></div>
<div class="cs_show_surname"><button type='button' class='cs_surname_button hidden' style='width:180px' value="Show_all">Show all</button></div>
<div class="cs_surname1">
<div class="cs_kb_cont">
<?php
foreach ($results as $result) {
if (count($results)<1){echo "No results found";}
else{
$sx = trim($result->sex);
?>
<div class='cs_kb_col_sn'>
<button type='button' class="my_btn" style='width:205px' value="<?php echo esc_js($result->ref);?>" name="<?php echo esc_js($result->surname);?>">
<?php
if (($sx)=== 'M'|| ($sx)=== 'm'){
echo ucfirst($result->given) . " " . ucfirst($result->surname) ." ♂ </button></div>";}
else {
echo ucfirst($result->given) . " " . ucfirst($result->surname) ." ♀ </button></div>";}
}
}
?>
</div></div></div><div class="cs_clearfix"></div>
<script>
jQuery(".my_btn").click(function(){
var ind = jQuery(this).val();
var na = jQuery(this).text();
jQuery.get(ajaxurl,{'action': 'getind', 'indv': ind, 'nme': na },
function (msg) { jQuery(".result_area_ind").html(msg);});
jQuery('.result_area_ind').removeClass("hidden");
jQuery('.result_area').removeClass("hidden");
jQuery('.cs_surname_button').removeClass("hidden");
jQuery('.cs_surname1').addClass("hidden");
});
jQuery(".cs_surname_button").click(function(){
jQuery('.cs_surname1').removeClass("hidden");
jQuery('.cs_surname_button').addClass("hidden");
//jQuery('.result_area').show();
jQuery('.result_area_ind').addClass("hidden");
});
</script>
<?php
//return ob_get_clean();
echo ob_get_clean();
wp_die();
}