Skip to content
Advertisement

How do I use specific table row data in ajax post

I’m trying to click on my pay button so as to update payment to a particular company. Below is my UI enter image description here

clicking on the pay button shows this enter image description here

I would like to display the name of the company the payment is going to and also be able to update the payment on the Total Remit column as well as reduce the debt.

I have been stuck on this page for a long time. Below is my code so far: query

error_reporting( E_ALL );
try{

  $sql='select c.catid, c.`category`,
      ifnull(sum( s.`stock_in` * s.`stock_price` ),0) as `debt`, c.`remitted`
  from `tbl_category` c
      left outer join `tbl_stock_in` s on s.`category_name` = c.`category`
  group by c.`category` order by catid desc;';


  $stmt=$pdo->prepare( $sql );
  $stmt->execute();
  
}catch( PDOException $e ){
  echo $e->getMessage();
}

code for table

    <?php
    
    while( $rs=$stmt->fetch(PDO::FETCH_OBJ ) ){
    
    echo'
    <tr>
    <td>'.$rs->catid.'</td>
    <td>'.$rs->category.'</td>
    <td>
      '.number_format($rs->debt,2).'
    </td>
    <td>'.number_format($rs->remitted,2).'</td>


    <td>
<button id='.$rs->catid.' class="btn btn-info btnremit"><span class="glyphicon glyphicon-eye-open" style="color:#ffffff" data-toggle="tooltip" title="Pay Company"></span></button>  
    
    </td>
    
    <td>
<a href="#.php?id='.$rs->catid.' class="btn btn-info" role="button"><span class="glyphicon glyphicon-edit" style="color:#ffffff" data-toggle="tooltip" title="Edit Category"></span></a>   
    
    </td>
    
    <td>
<button id='.$rs->catid.' class="btn btn-danger btndelete" ><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip"  title="Delete Category"></span></button>  
    
    </td>
     </tr>
     ';
    
}          
?> 

Here is my ajax

<script>
     
    $(document).ready(function() {
    $('.btnremit').click(function() {
      //var tdh = $(this);
      var id = $(this).attr("id");

        swal("Enter Amount:", {
            buttons: true,
            closeModal: true,
            content: "input",
        })
        .then((amount) => {
            if (amount === "") {
                    swal("Oops!! You need to enter value.");
                return false
            }else{
                $.ajax({
                    type: 'POST', 
                    url: 'remit.php',
                    data:{rid: id, pay: amount,
                      <?php 
              echo  ' currentDate : "'.$savedate.'", //working
                      compnyName : "'#'", //how do i call the company name that is clicked
                      old_remit : "'#'",//how do i fetch the old remit from the table
                                  '
                      ?>
                    },
                    success: function(data){
                         swal(`Paid: ${amount}`);
                    },
                    error: function(data){
                        swal(`Error remitting: ${amount}`);
                    }
                });
            }
            
          
        });
    
        });
    });


</script>

code for remit.php*

<?php
    
    #stock-in.php
    /*
        If you are using sessions you need to start a session!
    */
    error_reporting( E_ALL );
    session_start();

    if( empty( $_SESSION['useremail'] ) OR empty( $_SESSION['role'] ) OR $_SESSION['role']=="Admin" ){
        exit( header('Location: index.php') );
    }

    /*
        Check that all fields that are required in the sql have been submitted
    */
    if( isset( 
            $_POST['rid'],
            $_POST['pay'],
            $_POST['currentDate'],
            $_POST['compnyName'],
            $_POST['old_remit']
        ) ){

        try{
            
            include_once 'connectdb.php';

            /*
                When inserting, updating multiple tables there is some sense in using a transaction
                so that if one part fails the db is not littered with orphan records
            */
            $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $pdo->beginTransaction();

            $remitID            =   $_POST['rid'];
            $new_remit          =   (double)$_POST['pay'];
            $current_date       =   $_POST['currentDate'];
            $company            =   $_POST['compnyName'];
            $old_rem            =   (double)$_POST['old_remit'];

            $paid               =   $new_remit +  $old_rem;

            /*
                The sql command should use placeholders rather than embedded variables - the names are arbitrary
            */
            $sql='INSERT INTO `tbl_category_remits` ( `payment_date`, `category`, `remitted` ) 
                VALUES 
            ( :pay_date, :comp, :remit, :price, :cost, :current_times )';
            $stmt=$pdo->prepare( $sql );
            $args=array(
                ':pay_date'        =>  $current_date,
                ':comp'            =>  $company,
                ':remit'           =>  $new_remit

            );
            if( !$stmt->execute( $args )  )echo 'stmt#1 failed';
            
            
            
            $sql='UPDATE `tbl_category` SET `remitted` =:payment WHERE `catid`=:rid';
            $stmt=$pdo->prepare( $sql );
            $args=array(
                ':payment'    =>  $paid,
                ':rid'      =>  $remitID
            );
            if( !$stmt->execute( $args ) )echo 'stmt#2 failed';
            
            
            
            /*
                If it all went well, commit these statements to the db
            */
            if( !$pdo->commit() )echo 'commit failed';
            
            
        
        }catch( PDOException $e ){
            /*
                Any problems, rollback the transaction and report issues - 
                not necessarily with the full `getMessage()` ~ perhaps just
                'Error!' etc
            */
            $pdo->rollBack();
            
            echo $e->getMessage();
        }
    }
?>

Please, how do I fetch the company name and old remit from the table when I click on pay. I need your help!!

Advertisement

Answer

Instead

$(document).ready(function() {
    $('.btnremit').click(function() {
      //var tdh = $(this);
      var id = $(this).attr("id");
    })
})

You could use function where u can pass id,name etc.

function yourFunction(id,companyName,oldRemit){
    swal("Enter Amount:", {
        buttons: true,
        closeModal: true,
        content: "input",
    })
    .then((amount) => {
        if (amount === "") {
                swal("Oops!! You need to enter value.");
            return false
        }else{
            $.ajax({
                type: 'POST', 
                url: 'remit.php',
                data:{
                    rid: id, 
                    pay: amount,
                    compnyName : companyName,
                    old_remit : oldRemit,
                  <?php 
                   echo 'currentDate : "'.$savedate.'"'
                  ?>
                },
                success: function(data){
                     swal(`Paid: ${amount}`);
                },
                error: function(data){
                    swal(`Error remitting: ${amount}`);
                }
            });
        }
    });
}

And from your html table row call this function like

<td>
<button onclick="yourFunction('.$rs->catid.','.$rs->category.','.$rs->remitted.')" id='.$rs->catid.' class="btn btn-info btnremit"><span class="glyphicon glyphicon-eye-open" style="color:#ffffff" data-toggle="tooltip" title="Pay Company"></span></button>  
    
</td>

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement