I have a private front-end dashboard that allows a user to manage their client information, documents, etc – essentially a CRM. On one particular page, the clients are all loaded onto the page on load, and then each client has additional information that is loaded via ajax to ensure I am not bogging the website down.
Now it all works just fine, but as the subject line mentions, I get 20 calls to admin-ajax.php when the function runs, and all return successfully. So I’d like to get this figured out while I am in development rather than it becoming a resource issue later on.
I am using the below function to handle the AJAX request, the scripts.js file below contains the script I’ve included lower down. Depending on which tab is clicked, I then load a specific template:
//prep the JS + Ajax
function cyber_load_scripts() {
wp_enqueue_script('cyber_script', get_stylesheet_directory_uri() . '/js/scripts.js', array('jquery'), false, true );
wp_localize_script('cyber_script', 'cyberAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'cyber_load_scripts');
function ajax_load_tabs() {
$tab_id = $_REQUEST['id'];
$user_id = $_REQUEST['userid'];
if (str_contains($tab_id,'#onboarding')) {
get_template_part( '/page-templates/dashboard/broker-dashboard', 'onboarding', array (
'user_id' => $user_id,
));
}
elseif (str_contains($tab_id,'#tasks')) {
get_template_part( '/page-templates/dashboard/broker-dashboard', 'tasks', array (
'user_id' => $user_id,
));
}
elseif (str_contains($tab_id,'#incidents')) {
get_template_part( '/page-templates/dashboard/broker-dashboard', 'incidents', array (
'user_id' => $user_id,
));
}
die();
}
add_action('wp_ajax_ajax_load_tabs', 'ajax_load_tabs');
add_action('wp_ajax_nopriv_ajax_load_tabs', 'ajax_load_tabs');
And the script that initializes the ajax call when the client clicks on the tab. I skip the first tab as that is loaded with the page. I then pass the tab ID and the user ID to the AJAX request:
$( ".tabContent" ).each(function(index) {
$('.profileTabs ul li a').click(function(e) {
e.preventDefault();
//The first tab (overview) loads with the page
if($(this).text().match('Overview')) {
return false;
}
else {
var tab_id = $(this).attr('href');
var userid = $(this).attr('data-user');
$.ajax({
url: cyberAjax.ajaxurl,
data: ({
action: 'ajax_load_tabs',
id: tab_id,
userid: userid,
}),
success: function(data){
$(tab_id).html(data);
},
error: function(data)
{
//alert("Error!");
console.log("Error!");
return false;
}
});
}
});
Any ideas how I can make this call only once as intended? See below screen shot for reference:
