How to put a json returned from an API within a select?

Asked

Viewed 467 times

0

I am trying to make the credit card payment form, using the pay.me. I would like to calculate the installments via API and return them within a . I can return the json and return it to the console.log. But I don’t know how to get it into the .

HTML:

<form id="payment_form" action="pay_creditcard_pagarme.php" method="POST">
<div id="form">
    Número do cartão: <input type="text" id="card_number" maxlength="16" />
    <br />

    Nome (como escrito no cartão): <input type="text" id="card_holder_name" />
    <br />

    Mês de expiração: <input type="text" id="card_expiration_month" />
    <br />

    Ano de expiração: <input type="text" id="card_expiration_year" />
    <br />

    Código de segurança: <input type="text" id="card_cvv" />
    <br />

    <select name="installment_quantity" id="select-installments">
        <option selected>1</option>
    </select>
    <br><br>
</div>

    <input type="submit" value="Pagar">
</form>

Javascript:

$("#card_number").keyup(function(){
        var cardNumber = $("input[id='card_number']").val();

        //if creditcard number is finished, get installments
        if(cardNumber.length != 16){
            return;
        }

        pagarme.client.connect({ api_key: 'my_api_key' })
          .then(client => client.transactions.calculateInstallmentsAmount({
            id: 1234,
            max_installments: 3,
            free_installments: 2,
            interest_rate: 2,
            amount: 1000
          }))
          .then(installments => {

            console.log(JSON.stringify(installments));

            // Acredito que a partir deste ponto algo está errado.
            inst = installments;
            $("#select-installments").html("");
            for(var installment in inst.length){
                $("#select-installments").append("<option value='" + inst.installment + "'>" + inst.installment + " x R$ " + inst.installment_amount + " - " + (inst.installment <= 3? "Sem" : "Com")  + " Juros</option>");
            }

            });


    });

Console result.log:

{"installments":{"1": 
{"installment":1,"amount":1000,"installment_amount":1000},"2": 
{"installment":2,"amount":1000,"installment_amount":500},"3": 
{"installment":3,"amount":1060,"installment_amount":353}}}

2 answers

1

Try this code:

//data
var d = {"installments":
    {"1": {"installment":1,"amount":1000,"installment_amount":1000},
    "2": {"installment":2,"amount":1000,"installment_amount":500},
    "3": {"installment":3,"amount":1060,"installment_amount":353}}}

    console.log(d.installments); //obtém tudo
    console.log(d.installments[1].installment); //primeiro registro.
    console.log(d.installments[1].amount); //primeiro registro.
    console.log(d.installments[1].installment_amount); //primeiro registro.


    console.log(d.installments[2]); //segundo registro.
    //etc.

    let data = d.installments;
    for(let index in data){
    
    //Exemplo para inserir no HTML

      $("#select-installments").append("<option value='" + data[index].amount+ "'>" + data[index].amount+ " x R$ " + data[index].amount + " - " + (data[index].amount <= 3? "Sem" : "Com")  + " Juros</option>");
      
    console.log(data[index].installment);
    console.log(data[index].amount);
    console.log(data[index].installment_amount);
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<select name="installment_quantity" id="select-installments">
    <option selected>1</option>
</select>

1


It is necessary to pick up the objects inside installments return with the same name. It would be:

let inst = installments.installments;

The first installments is what comes from the return of the function, the second is an object within the return, where there are other objects from where you want to get the information.

In the for you will not use .length because it is not an array, but rather a collection of objects, and in this type of for does not need to know the size of what you will iterate.

Instead of using $("#select-installments").html(""); to empty select, use a method suitable for this, .empty(): $("#select-installments").empty();

And instead of <=3, should be <3 (less than 3), if not the option "with interest" will be "interest-free".

Your code would look like this, where I simulated the return of the function with a variable installments simple:

installments = {"installments":{"1": 
{"installment":1,"amount":1000,"installment_amount":1000},"2": 
{"installment":2,"amount":1000,"installment_amount":500},"3": 
{"installment":3,"amount":1060,"installment_amount":353}}}

// copie somente daqui pra baixo
let inst = installments.installments;
$("#select-installments").empty();
for(let i in inst){
   $("#select-installments").append("<option value='" + inst[i].installment + "'>" + inst[i].installment + " x R$ " + inst[i].installment_amount + " - " + (inst[i].installment < 3? "Sem" : "Com")  + " Juros</option>");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="installment_quantity" id="select-installments">
   <option selected>1</option>
</select>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.