0

I have tried so hard to do this but can't get it to work. I basically need to get the name/id of the current bootstrap 4 tab using jquery (from bootstrap docs) and pass it into a PHP variable to then use in MySQL WHERE clause to determine what data to show for that tab.

This is my code so far:

 <script>
        $(document).ready(function(){
            $('.nav-tabs a').on('click', function (e) {
                e.preventDefault()
                $(this).tab('show')
              })
            $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) 
            {
                var x = $(e.target).text();
                console.log(x);
                $(".act span").text(x);

                $.ajax({
                type: 'post',
                url:'contacts_1.php',
                data:{'activeTab' : x},
                success:function(result){
                    $('body').html(result);
                }
                });
            });
       });
</script>

Then at the top of the page, I am trying to access the variable like so -

<?php
if( isset($_POST['activeTab']))
{
    $currenttab = $_POST['activeTab'];
    echo $currenttab;
}
?>

** Update - I have now got the tabs to work (updated my code) (although I can't get the tab to stay 'active' - that's another problem). But when I get my posted variable at the top of my php page, I cannot use it further down my page in my WHERE clause. I am getting the error 'undefined variable'. Any help?

Below is my php page code -

<?php

if( isset($_POST['activeTab'])){
            $currenttab = $_POST['activeTab'];
            echo $currenttab;
        }
?>
<!DOCTYPE html>
<html>
   <head>
        <meta charset="UTF-8"> 
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <link rel="stylesheet" href="styles.css">
        <title></title>
    </head>
    <body>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>


   *some other html here just displaying a photo*

       <ul class='nav nav-tabs'>    

       <?php
        include('connect.php');

        $tabs = "SELECT DISTINCT tab FROM table";

        $result = oci_parse($conn, $tabs);
        oci_execute($result);

        while (($row = oci_fetch_assoc($result)) != false) {
            $area = $row['TAB'];
            $output = '';
            $output03= '';

            echo " <li class='nav-item'>
                        <a class='nav-link' id='home-tab' data-toggle='tab' href='#" .$area. "' role='tab' aria-controls='home' aria-selected='true'>$area</a>
                   </li>";

             $output .= "<div class='tab-pane fade show active' id='" .$area. "' role='tabpanel' aria-labelledby='home-tab'>";

             $output03 .= '</div>';
        }

        ?>     

         </ul>         

        <div class='tab-content mt-4'>
        <div class='row'>

      <?php

        echo $output;

        $query = "SELECT field1, field2, ...     
                FROM table1, table2,....
                WHERE ... = ... AND
                     TAB = '$currenttab'";

        $stid = oci_parse($conn, $query);
        oci_execute($stid);

        while (($row = oci_fetch_assoc($stid)) != false) {
            $name = $row['EMPNAME'];
            $emprole = $row['ROLE'];
            $empext = $row['EXTENSION'];

            echo "<br>
               <div class='col-md-4'>
                 <div class='card' style='width: 18rem;'>
                   <img class='card-img-top' src='img_avatar.png' alt='Card image cap'>
                    <div class='card-body text-centered'>
                     <a data-toggle='collapse' href='#moreinfo1' role='button' aria-expanded='false' aria-controls='collapseExample'>
                        <h5 class='card-title'>$name</h5>
                      </a>

                 <p class='card-text'><i class='fa fa-fw fa-user'></i>$emprole</p>
                                        <hr>
                 <p class='card-text'><i class='fa fa-fw fa-phone'></i>$empext</p>
                </div>
               </div>
             </div> ";
        }

        echo $output03;

        ?>

</div>
       <script>
        $(document).ready(function(){
            $('.nav-tabs a').on('click', function (e) {
                e.preventDefault()
                $(this).tab('show')
              })
            $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) 
            {
                var x = $(e.target).text();
                console.log(x);
                $(".act span").text(x);

                $.ajax({
                type: 'post',
                url:'contacts_1.php',
                data:{'activeTab' : x},
                success:function(result){
                    $('body').html(result);
                }

                });
            });
       });
        </script>
    </body>
</html>

bb25
  • 55
  • 1
  • 8
  • 1
    Isn’t this is same as your other question you asked a few hours ago ? https://stackoverflow.com/questions/59877058/how-to-use-bootstrap-tabs-with-dynamic-data-coming-from-database-in-php-while-lo –  Jan 23 '20 at 18:08
  • Shouldn't you remove the quotes? `data:{activeTab: x},` – brombeer Jan 23 '20 at 18:08
  • Similar but not the same as my question has gotten more specific. Do you have an answer or something? @Dilek – bb25 Jan 23 '20 at 18:11
  • I had it without quotes to start with and it didn’t work but then saw on another answer on here that you should have quotes and that it worked for the person lol - not working either way :( thank you @kerbholz – bb25 Jan 23 '20 at 18:15
  • @kerbholz the quotes on the object key don't matter. With or without, result in the same object. – Taplar Jan 23 '20 at 18:22
  • What do you get when you console `x`. Try writing `console.log(x);` after line = `var x = $(e.target).text(); ` – Amanjot Kaur Jan 24 '20 at 07:03
  • Also, just for a suggestion, you had not added `datatype` in ajax call. https://stackoverflow.com/questions/2722750/ajax-datatype – Amanjot Kaur Jan 24 '20 at 07:31
  • I am now getting the correct output printed to the console. (I was using a slim build version of jquery). However, it only works with the first tab clicked when the page loads and no more. Meaning I have to manually refresh the page and click a different tab for it's value to print to the console. – bb25 Jan 24 '20 at 09:11

1 Answers1

0

Try

 <script>
    $(document).ready(function(){
        $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e)
        {
            var x = $(e.target).text();
            console.log(x);

            $.ajax({
                url: 'contacts_1.php',
                type: 'post',
                 data:{'activeTab' : x},
                datatype: 'html',
                success: function (rsp, status, jqXHR) 
                {
                     $('.tab-content').html(rsp);
                }
            });
        });
    });
</script>

To capture events on elements that are created AFTER declaring your event listeners - you should bind to a parent element or element higher in the hierarchy.

PHP Code:

<?php
if( isset($_POST['activeTab']))
{
    $currenttab = $_POST['activeTab'];
    ?>

          <?php
            $query = "SELECT field1, field2, ... FROM table1, table2,.... WHERE ... = ... AND TAB = '$currenttab'";
            $stid = oci_parse($conn, $query);
            oci_execute($stid);
            while (($row = oci_fetch_assoc($stid)) != false) {
                $name = $row['EMPNAME'];
                $emprole = $row['ROLE'];
                $empext = $row['EXTENSION'];

               ?>
                <div class='col-md-4'>
                     <div class='card' style='width: 18rem;'>
                       <img class='card-img-top' src='img_avatar.png' alt='Card image cap'>
                       <div class='card-body text-centered'>
                            <h5 class='card-title'><?php echo $name ?></h5>
                            <p class='card-text'><i class='fa fa-fw fa-user'></i><?php echo $emprole ?></p>
                            <hr>
                        <p class='card-text'><i class='fa fa-fw fa-phone'></i><?php echo $empext ?></p>
                      </div>
                   </div>
                </div>
                <?php
            }
            ?>

    <?php
}
?>
Amanjot Kaur
  • 2,028
  • 4
  • 18
  • 33
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/206586/discussion-on-answer-by-amanjot-kaur-use-ajax-to-load-dynamic-content-in-dynamic). – Samuel Liew Jan 24 '20 at 13:10
  • Thank you very much. Just wondering.. if I was to use more pages than one, would it then be possible with php? As in have the tabs linking to an actual separate page? – bb25 Jan 24 '20 at 13:11