Jump to content

Recommended Posts

Dear Team,

Based on the table row selection from my existing table and display all parameters to another table using Ajax query.

 

My table button is 

<td align='center'>                                
<a class="link"  href="#?edit=<?php echo $Approvel_id ; ?>" onclick="getProfileData(<?php echo $Approvel_id; ?>)">View</a>
</td>

 

Based on the Id selection on above button the values should display on bellow table

<div id="id02" class="w3-modal ">
                    <div class="container full border w3-modal-content w3-card-4 w3-animate-zoom w3-padding" style="margin:20px;padding:10px;overflow:auto;width:98%;height:auto">
                        <h2></h2><br /><br />
                        <div >
                            <br />
                            <span onclick="document.getElementById('id02').style.display='none'" class="w3-button w3-xlarge w3-hover-red w3-display-topright" title="Close Modal">&times;</span>
                        </div>

                        <div class="tbl-header">

                            <table cellpadding="0" cellspacing="0" border="0">
                                <thead>
                                    <tr>
                                        <th align='center' style="width:4%">S.No</th>
                                        <th style="width:25%">Description</th>
                                        <th style="width:25%">Ratings</th>
                                        <th style="width:5%">Target</th>
                                        <th style="width:5%">Actual</th>
                                        <th style="width:17%">Remarks</th>
                                        <th style="width:20.5%">Document</th>
                                    </tr>
                                </thead>

                                <tbody>
                            
                                    <tr>
                                        <td align='center' style="width:4%">
                                            <?php echo $n++; ?>
                                        </td>
                                        <td style="width:25%">
                                            <span id="Point_Description"></span>
                                        </td>
                                        <td align='center' style="width:5%">
                                            <span id="Point_Marks"></span>
                                        </td>
                                        <td style="width:25%">
                                            <span id="Marks_Target"></span>
                                        </td>
                                        <td align='center' style="width:5%">
                                            <span id="Marks_Actual"></span>
                                        </td>
                                        <td align='center' style="width:5%">
                                            <span id="Marks_Description"></span>
                                        </td>
                                        <td align='center' style="width:19%">

                                            <a href=" http://localhost:15296/<?php echo $Directory; ?>/<?php echo $Document; ?>" target="_blank">
                                                <?php echo $Document; ?>
                                            </a>
                                        </td>
                                    </tr>
                              
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>

My ajax query is 

      <script>
    function getProfileData(id) {
        $.ajax({
            method: "GET",            
            url: "User_Statment_view.php?id=" + id,
                        success:   function(data){
                           var tmp = data.split("&");
                           $('#Point_Marks').html(tmp[0]);
                           $('#Point_Marks').html(tmp[1]);
                            $('#Marks_Target').html(tmp[2]);
                            $('#Marks_Actual').html(tmp[3]);
                            $('#Marks_Description').html(tmp[4]);
                            $('#Document').html(tmp[5]);
                            $('#Directory').html(tmp[6]);
                            $('#id02').show();
            }
                                    
        })
    }
        </script>

 

My User_Statment_view.php code is 

<?php

include("connection.php");
if(isset($_GET['id'])){
    $ID = $_GET['id'];


    $query = "SELECT* FROM approvel where Approvel_id={$ID}";
    $result = mysqli_query($conn, $query);
    $row1 = mysqli_fetch_array($result);

    $Name = $row1['Emp_Name'];
    $Month = $row1['Month'];

    $sql = "SELECT * FROM marks WHERE Engg_Name = '$Name' AND Month = '$Month' ";
    $result1 = mysqli_query($conn,$sql);

    $array[] = array();
          while($row  =   mysqli_fetch_assoc($result1)){
              $array[] = $row;
             }

          echo $array[0]['Point_Description']. '&';   
          echo $array[1]['Point_Marks']. '&';
          echo $array[3]['Marks_Target']. '&';
          echo $array[4]['Marks_Actual']. '&';
          echo $array[5]['Marks_Description']. '&';
          echo $array[6]['Document']. '&';
          echo $array[7]['Directory'];

}

 

When i am running my code, i am getting 14 array values on my  User_Statment_view.php and my table i am getting only one row value instead of 13 row values.

image.thumb.png.61941c5eb6bfcdbf98a1858c46707994.png

 

can any one help me how to get all my 13 rows on this table.

Link to comment
https://forums.phpfreaks.com/topic/315672-problem-on-ajax-get-function/
Share on other sites

IDs in an html document must be unique. Every time you set the content of $('#Point_Marks') you are writing to the same element.

A better approach is to json encode your query results and return the json object in your response, then do something like this

function(resp) {
    $("#orderbody").html("")                            // clear output table's tbody section tag
    $.each(resp, function(k, row) {                
        let newrow = $("<tr>")                          // create new row
        $.each(row, function(k1, col) {
            let newcol = $("<td>", {"text":col})            // ceate new col with content
            $(newrow).append(newcol)                        // append to row
        })
        $("#orderbody").append(newrow)                  // append row to tbody
    })
},

 

I can give you a complete example script so you can see how it all fits together plus some test data.

Output sample

image.png.9331efeb5100e8cd5b174e235dc5afde.png

Code

<?php
 const HOST     = 'localhost';
 const USERNAME = '????';
 const PASSWORD = '????';
 const DBNAME   = '????';
 
     // PDO database connection
     //
         $dsn = "mysql:dbname=".DBNAME."; host=".HOST."; charset=utf8";
         $pdo = new pdo($dsn, USERNAME, PASSWORD,
         [
             PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
             PDO::ATTR_EMULATE_PREPARES => false,
             PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
         ]);
         

################################################################################
#  HANDLE AJAX REQUEST                                                         #
################################################################################
    if (isset($_GET['ajax']))  {
        
        if ($_GET['ajax']=='getorders')  {
            $res = $pdo->prepare("SELECT order_id  as oid
                                       , date_format(order_date, '%b %D %Y') as odate
                                  FROM ba_orders
                                  WHERE client_id = ?
                                  ORDER BY order_date     
                                  ");
            $res->execute( [ $_GET['id'] ] );
            $results = $res->fetchAll();
            if (count($results)==0) $results = [['No orders', '']];
            exit(json_encode($results));
        }
        
        else exit('INVALID REQUEST');
    }

################################################################################
#  GET THE CLIENT DATA FOR DISPLAY                                             #
################################################################################
    $cdata = '';
    $res = $pdo->query("SELECT client_id
                             , name
                        FROM ba_client 
                        ORDER BY name     
                       ");
    foreach ($res as $clt) {
        $cdata .= "<tr><td>{$clt['client_id']}</td>
                       <td class='client-name' data-id='{$clt['client_id']}'>{$clt['name']}</td>
                  </tr>\n";
    }
?>
<!DOCTYPE=html>
<html>
<head>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type='text/javascript'>
    $(function() {
        $(".client-name").click( function() {
            let cid = $(this).data("id")
            $(".client-name").css("background-color", "white")
            $(this).css("background-color","#eee")
            $.get (
                "",                                                     // request sent to self
                {"ajax":"getorders", "id":cid},
                function(resp) {
                    $("#orderbody").html("")                            // clear output table's tbody section
                    $.each(resp, function(k, row) {                
                        let newrow = $("<tr>")                          // create new row
                        $.each(row, function(k1, col) {
                            let newcol = $("<td>", {"text":col})            // ceate new col with content
                            $(newrow).append(newcol)                        // append to row
                        })
                        $("#orderbody").append(newrow)                  // append row to tbody
                    })
                },
                "JSON"
            )
        })
    })
</script>
<style type='text/css'>
    td.client-name {
        cursor: pointer;
        color: blue;
    }
    td.client-name:hover {
        border: 1px solid red;
        text-decoration: underline;
    }
</style>
</head>
<body>
<header class='w3-container w3-padding'>
</header>
<div class='w3-container w3-padding'>
    <div class='w3-row-padding'>
        <div class='w3-col w3-half w3-padding'>
            <h3>Clients</h3>
            <table class='w3-table w3-bordered'>
            <thead>
                <tr class='w3-blue-gray'><th>Client ID</th><th>Client Name</th></tr>
            </thead>
            <tbody id='clbody'>
                <?=$cdata?>
            </tbody>    
            </table>
        </div>
        <div class='w3-col w3-half w3-padding'>
            <h3>Orders</h3>
            <table class='w3-table w3-bordered'>
            <thead>
                <tr class='w3-blue-gray'><th>Order ID</th><th>Order Date</th></tr>
            </thead>
            <tbody id='orderbody'>
            </tbody>    
            </table>
        </div>
    </div>
</div>

</body>
</html>

Data

CREATE TABLE `ba_client` (
  `client_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`client_id`)
) ENGINE=InnoDB;

INSERT INTO `ba_client` VALUES (1,'Dancer'),(2,'Prancer'),(3,'Dasher'),(4,'Vixen'),(5,'Comet'),(6,'Cupid'),(7,'Donner'),(8,'Blitzen');


CREATE TABLE `ba_orders` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `client_id` int(11) DEFAULT NULL,
  `order_date` date NOT NULL DEFAULT '0000-00-00',
  PRIMARY KEY (`order_id`),
  KEY `idx_order_client` (`client_id`)
) ENGINE=InnoDB;

INSERT INTO `ba_orders` VALUES (1,5,'2022-12-01'),(2,5,'2022-12-02'),(3,7,'2022-12-03'),(4,3,'2022-12-04'),(5,6,'2022-12-05'),
(6,4,'2022-12-06'),(7,7,'2022-12-07'),(8,2,'2022-12-08'),(9,4,'2022-12-09'),(10,3,'2022-12-10'),(11,3,'2022-12-11'),
(12,4,'2022-12-12'),(13,7,'2022-12-13'),(14,2,'2022-12-14'),(15,6,'2022-12-15'),(16,8,'2022-12-16');

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.