Friday, November 11, 2022

[FIXED] How to set amount of an item dynamically in javascript

Issue

I am trying to integrate a payment gateway on my website. Here is my code

products.php

<div class='row footer'>
 <div class='col-5 col-lg-5'>
    <button class='btn btn-action kkiapay-button' 
      amount-price='" . $row['price'] . "' 
      onclick='openKkiapayWidget()'>" . $row['action'] . "
    </button>
 </div>
 <div class='col-7 col-lg-7 price'>
    <span>XOF " . number_format($row['price']) . "</span>
 </div>
</div>

main.js

openKkiapayWidget({
    amount:"50000",
    position:"center",
    callback:"",
    theme:"red",
    key:"< my-api-key >"
});

Now, the problem is that there are many products with different prices; but here I can only put a static amount (50000) which applies to all products when the action button is clicked. Is there any way I can dynamically get the price of products and set it in my function in case of a product that has a different price?

I tried this but it doesn't work

var price = $(this).amount("price");
openKkiapayWidget({
    amount:""+price+"",
    position:"center",
    callback:"",
    theme:"red",
    key:"<my-api-key>"
});

Solution

Pass the element as argument to a "new" function to handle the price before calling your widget. It can be done using this between the parenthesis of the onclick function call. Then you will be able to retreive the price from the amount-price attribute.

<div class='row footer'>
 <div class='col-5 col-lg-5'>
    <button class='btn btn-action kkiapay-button' 
      amount-price='" . $row['price'] . "' 
      onclick='openKkiapayWidgetWithPrice(this)'>" . $row['action'] . "
    </button>
 </div>
 <div class='col-7 col-lg-7 price'>
    <span>XOF " . number_format($row['price']) . "</span>
 </div>
</div>

function openKkiapayWidgetWithPrice(button)
  let price = button.getAttribute("amount-price");
  
  // The call to your widget
  openKkiapayWidget({
      amount: price,
      position: "center",
      callback: "",
      theme: "red",
      key: "< my-api-key >"
  });
}

If amount-price includes a currentcy symbol, you have to remove it.



Answered By - Louys Patrice Bessette
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.