0

I have ajax which takes data (id, companyName, owed, oldRem) from a table in categorylist.php which is used in remit.php. Below is my ajax code categorylist.php which gets data from table row and it works well.

<script>
     function payCompany(id, companyName, owed, oldRemit){
        swal("Enter Amount:", {
            title: companyName,
            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, 
                    company_Name: companyName,
                    old_Remit: oldRemit,
                    debt_owed: owed,
                      <?php 
                            echo  ' currentDate : "'.$savedate.'",'
                      ?>
                    },
                    success: function(data){
                         swal(`Paid: ${amount} to ${companyName}`);
                    },
                    error: function(data){
                        swal(`Error remitting: ${amount} to ${companyName}`);
                    }
                });
            } 
        });
     }


</script>

my code in remit.php. I couldn't confirm if the code is passed to remit.php from ajax. there was no error displayed when it was run.

<?php
    
    #remit.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'],
            $_POST['debt_owed']
        ) ){

        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'];
            $company            =   $_POST['compny_Name'];
            $old_rem            =   (double)$_POST['old_remit'];
            $total_debt         =   (double)$_POST['debt_owed'];
            $current_date       =   $_POST['currentDate'];

            $paid               =   $new_remit +  $old_rem;
            $currentDebt        =   $total_debt - $paid;

            /*
                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 )';
            $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 , `debt` =:current_debt WHERE `catid`=:rid';
            $stmt=$pdo->prepare( $sql );
            $args=array(
                ':current_debt'     =>  $currentDebt,
                ':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();
        }
    }else{
        echo $e->getMessage();
    }
?>

On the above code, I have an insert statement as well as update statements, both to different tables as shown below: Table for SQL updating query

table for SQL query for inserting

Please, what's wrong with my code? It doesn't seem to update and insert into the database. Please, I need help with this code!!

Ambi
  • 53
  • 1
  • 1
  • 7
  • try to inspect your code with an `var_dump($e->getMessage()); die;` instead of `echo` and look at the developer tools of your browser , since you are using an ajax call. – André Walker Dec 19 '20 at 22:23
  • Have you tried running the post-request by hand (e.g. with [curl on the command line](https://stackoverflow.com/questions/356705/how-to-send-a-header-using-a-http-request-through-a-curl-call)) and see if you get any output? – ArSeN Dec 19 '20 at 22:23
  • @AndréWalker, I have tried what you suggested, and still no error. I use edge browser as well as chrome – Ambi Dec 19 '20 at 22:30
  • @ArSeN, how do I do the post-request by hand? I'm still new to this. I need your guide pls. – Ambi Dec 19 '20 at 22:31
  • @UgochukwuAnajemba That is why I linked a guide in my previous comment ;) – ArSeN Dec 19 '20 at 22:33
  • ok, will check it out. thanks. – Ambi Dec 19 '20 at 22:34
  • @ArSeN If the success: function (data) if Ajax displays a message, isn’t it an indication that the data was passed to remit.php? I think the problem somehow is in my sql query but I can’t figure out the exact problem. – Ambi Dec 20 '20 at 05:41

0 Answers0