how to built ajax tabs in wordpress?

admin

Administrator
Staff member
I try to display the departments in my website as tabs, when click one tab it will display the data related to this department according to department_id.

I try this code <a href="https://stackoverflow.com/questions...1332113?noredirect=1#comment50652111_31332113">Execute php function only when clicked (wordpress)</a> but I need the tabs number to be dynamic.

Code:
&lt;div class="tabs"&gt;
&lt;ul&gt;
    &lt;?php
        $arr1=array(2,3,5,10,22,25,27,28,29,30);    

        $arr2=array("dep1","dep2","dep3","dep4",
        "dep5","dep6","dep7","dep8","dep9","dep10");

        for($i=0;$i&lt;10;$i++){?&gt;
            &lt;li&gt;&lt;a href="#tab" id="&lt;?php echo $arr1[$i]; ?&gt;"&gt;&lt;?php echo 
                 $arr2[$i];?&gt;
            &lt;/a&gt;&lt;/li&gt;
    &lt;?php  } ?&gt;
 &lt;/ul&gt;
 &lt;/div&gt;


 &lt;div id="tab" class="section"&gt;

 &lt;/div&gt;

functions.php:

Code:
&lt;?php
 add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');

function tabsfunction() {
$dept_id=$_GET[id];
/** Here I print data according to $dept_id **/
die();
}
?&gt;

script.js:

Code:
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();

var tab_id = jQuery(this).attr('id'); 

console.log(tab_id);
                jQuery.ajax({
                    type: "GET",
                   url: "wp-admin/admin-ajax.php", 
                    dataType: 'html',
                    data: ({ action: 'tabsfunction', id: tab_id}),
                    success: function(data){
                               jQuery('#tab').html(data);
                    },
                  error: function(data)  
                    {  
                   alert("Error!");
                    return false;
                }  });}); });

it dose not work, it displays data only for one tab.
console.log(tab_id) ----> it display the id for the first tab clicked
and did not change when click another tab.