Send data via POST in javascript

Asked

Viewed 5,640 times

0

Guys I know almost nothing about JS, and I am developing a php system with help from Cakephp 3, the following is part of my payment screen, my problem is that I need to get the values that are in Javascript from total_sale, and also take the amount of products that is in php in my id_cart Session and pass to js to send via post as soon as I click the close sell button. I’m not sure how to take this data in my view and not treat it in my controller.

My modal:

    <!-- Button to Open the Modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-xl" style="width: 90%; font-size: 130%;">Pagar Venda</button>

    <!-- The Modal -->
    <div class="modal fade bd-example-modal-xl" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" style="width:90%">
            <div class="modal-content">
            <!-- Modal Header -->
                <div class="modal-header">
                    <h2 class="modal-title" style="text-align: center;">Formas de Pagamento</h2>                        
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>

                <!-- Modal body -->
                <div class="modal-body">
                    <br />
                    <table class="payment-methods">
                        <tr>
                            <td>
                                <input type="radio" name="payment_methods" id="dinheiro" class="pg" />
                                <label for="dinheiro" class="labelpag">
                                    <img src="/projeto/img/cash.png" class="imgpag" alt="" >
                                </label>
                                <br />
                            </td>

                            <td>
                                <input type="radio" name="payment_methods" id="credito" class="pg" />
                                <label for="credito" class="labelpag2">
                                    <img src="/projeto/img/card2.png" class="imgpag2">
                                </label>
                            </td>
                            <br />
                            <td>
                                <input type="radio" name="payment_methods" id="debito" class="pg" />
                                <label for="debito" class="labelpag2">
                                    <img src="/projeto/img/card.png" class="imgpag2">
                                </label>
                            </td>
                        </tr>
                    </table>

                    <table>
                        <tr>
                            <td>
                                <p class="p_pagamento totalpago">Total de Itens:
                                <?php
                                $id = $_SESSION['id_cart'];
                                $id = $id["id"];
                                    if(isset($id)){
                                        if($id == null){
                                            $id = 0;
                                        }
                                        echo count($id);?>
                                    <input type="hidden" name="produtos_id" value="$id">
                                    <?php
                                    } ?>
                                </p>
                            </td>
                            <td>
                                <p class="p_pagamento">Total da Venda: R$ <span class="total_venda"></p>
                            </td>
                        </tr>
                        <tr>
                            <td> 
                                <p class="p_pagamento"> Total Pago: R$ <input type="" name="troco" value="" class="input_pagamento" id="total_pago"></p>
                            </td>
                            <td>
                               <p class="p_pagamento trocopagamento"> Troco R$ 
                                <span id="troco"></span></p> 
                            </td>

                        </tr>
                    </table>
                        <br />
                        <button type="Submit" class="btn btn-primary" id="click">Fechar Venda</button>
                </div>
                <!-- Modal footer 
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>-->
            </div>
        </div> 
    </div>

Js:

<script>
function soma_total(){
    total = 0;
    $(".total_unitario").each(function() {
        total += parseFloat($(this).text());
    });
    $(".total_venda").text((total).toFixed(2));
    total_venda = $(".total_venda").text((total).toFixed(2));
};

var quantidade = 0;
var precounitario = 0;
var total = 0;

$(".quant").each(function(){
    quantidade = parseFloat($(this).val());
    precounitario = parseFloat($(this).parent().parent().find(".preco_uni").text());
    $(this).parent().parent().find(".total_unitario").text((quantidade*precounitario).toFixed(2));
    soma_total();
})

$(".quant").change(function(){
    quantidade = parseFloat($(this).val());
    precounitario = parseFloat($(this).parent().parent().find(".preco_uni").text());
    $(this).parent().parent().find(".total_unitario").text((quantidade*precounitario).toFixed(2));
    soma_total();
});


$("#total_pago").keyup(function(){
    var pago = $(this).val().replace(",",".");
    $("#troco").text((pago-total).toFixed(2));        
})

  • Do you already have the array/variable ready that receives the data? In case it would just pass the data to another page via _POST or also have limitations in assembling these variables?

  • In case it would be to send the data to my controller and it can save in the database.

1 answer

2


Hello,

There are a few ways to send posts to the server through javascript. The ideal is that you use forms in html itself, however for sending the post directly by javascript, the simplest way, is using the function ajax, jQuery library (which you already use). This function is responsible for executing an asynchronous HTTP request (in other words, it allows sending and handling the result of requests to the server). Take the example:

$.ajax({
   method: "POST",
   url: "servidor.php",
   data: {nome: "Lucas"}
});

Note that the message is by default sent as a JSON. Therefore on your server you should take care to read this message. In the case of PHP, use the function json_decode().


In your code, the script should look like this:

$(document).ready(function(){
    // aqui vai seu código já criado

    $("#click").on("click", function(){ // Quando o elemento do id "click" é clicado...
        var id_cart = $("#produtos_id").val(); // Pega o valor do campo produtos_id
        var total_venda = $(".total_venda").text(); // Pega o total

        $.ajax({
            method: "POST",
            url: "servidor.php",
            data: {idCart: id_cart, totalVenda: total_venda} // Dados a serem enviados
        });
    });
});


On the html page, it is important to add the id produtos_id to the same name field, otherwise jQuery will not be able to get the field’s value. See before and after:

<input type="hidden" name="produtos_id" value="$id">
<input type="hidden" id="produtos_id" name="produtos_id" value="$id">



I hope I helped, hug!

  • I used this code, made some tests and checked which script the variables declared as total_sale are passing the data, but when I try to finalize the purchase of variable error not defined... Maybe it’s a mistake in my controller but apparently it’s all right

  • Hello friend, try to close the total span in your html code. It should look like this: <p class="p_pagamento">Total da Venda: R$ <span class="total_venda"></span></p>. I believe the error is the time to pick up the text of this span, since the tag is not closed.

  • Lucas, so I checked, I made your code and I fixed the controller, the program runs no errors however the controller is not receiving the js post and apparently the code is correct.

  • I put my code in the next comment and showing the problem, thanks for the help

Browser other questions tagged

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