Get values of selected checkboxes and their respective prices

Asked

Viewed 1,591 times

3


Well, I’m developing an online ordering system, initially just for learning purposes, only that I came across something that I have absolutely no idea how to do and would really appreciate any kind of help.
On the page php products. I establish two connections with DB and look for the products in the table products by category and the increases in the table we believe:

$sql = "SELECT p.id_produto, p.nome_produto, p.preco_produto, p.id_categoria, c.nome_categoria FROM produtos p, categorias c WHERE c.id_categoria = p.id_categoria ORDER BY p.id_categoria, p.nome_produto";
$stmt = $conexao->prepare($sql);
$stmt->execute();

$sql2 = "SELECT id_acrescimo, nome_acrescimo, preco_acrescimo FROM acrescimos ORDER BY nome_acrescimo";
$stmt2 = $conexao->prepare($sql2);
$stmt2->execute();

$num = $stmt->rowCount();
$categoria = null;

if($num>0)
{
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        extract($row);
        if($categoria != $id_categoria)
        {
            if(!is_null($categoria)) { echo "</table>"; }

        echo "<h1>{$nome_categoria}</h1>
        <table>
            <tr>
                <th>NOME</th>
                <th>PREÇO</th>
                <th>QUANTIDADE</th>";
                if($id_categoria == 1) echo" <th>ACRÉSCIMOS</th>";
            echo "</tr>";

            $categoria = $id_categoria;
        }
        $preco_produto_reajustado = number_format($preco_produto, 2, ",", ".");
        echo "
        <tr>
            <td>
                <div class='id-produto' style='display: none'>{$id_produto}</div>
                <div class='nome-produto'>{$nome_produto}</div></td>
                <td>R&#36;{$preco_produto_reajustado}
            </td>
            <td>
                <input type='number' name='quantidade' value='1' min='1' max='20'/>
            </td>";
            if($id_categoria == 1)
            {
                echo "<td>";
                while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
                {
                    extract($row);
                    $preco_acrescimo_reajustado = number_format($preco_acrescimo, 2, ",", ".");
                    echo "
                    <input type='checkbox' name='{$nome_acrescimo}' value='{$nome_acrescimo}'/>{$nome_acrescimo} - R&#36;{$preco_acrescimo_reajustado} <input type='number' name='quantidade_acr[]' value='1' min='1' max='5'/><br/>
                    ";
                }
                echo "</td>";
            }
            echo "<td>
                <form class='adicionar'>
                    <button type='submit'>Adicionar</button>
                </form>
            </td>
        </tr>";
    }
    echo "</table>";
}

As you can see with this code, if the ID of the corresponding category is 1, another column will be created in the table. The column Additions. And that’s where my biggest problem lies. If you’ve analyzed the code well, you can see that my output will be something like: Output They noted the checkboxes present in the column Additions? So what I’m trying to do (unsuccessfully) is, in the act of click on the button Add, obtain the values of checkboxes selected according to their names and prices in the table we believe. But how to do that?
I need to get these values and store them in variables to later insert them into the SESSION and display them along with others in the user’s cart. In the php products. I have a function of jQuery which stores the data of the selected row in variables to be later inserted into its certain variables in the SESSION:

$(document).ready(function()
{
    $('.adicionar').on('submit', function()
    {
        var id_produto = $(this).closest('tr').find('.id-produto').text();
        var nome_produto = $(this).closest('tr').find('.nome-produto').text();
        var quantidade = $(this).closest('tr').find('input').val();
        window.location.href = "adicionar.php?id_produto=" + id_produto + "&nome_produto=" + nome_produto + "&quantidade=" + quantidade;
        return false;
    });
});

In the archive add.php i search in DB the ID and name of the selected product to then get the price of it. If my return is true, the script continues adding data to the SESSION:

if (isset($_GET['id_produto']) && $_GET['id_produto'] != "")
{
    if(isset($_SESSION['carrinho']))
    {
        $contar = count($_SESSION['carrinho']);
        $id_produto_sessao = $contar++;
    }
    else
    {
        $id_produto_sessao = 0;
    }
    $id_produto = isset($_GET['id_produto']) ? $_GET['id_produto'] : "";
    $nome_produto = isset($_GET['nome_produto']) ? $_GET['nome_produto'] : "";
    $quantidade = isset($_GET['quantidade']) ? $_GET['quantidade'] : "";

    $sql = "SELECT * FROM produtos WHERE id_produto LIKE '{$id_produto}' AND nome_produto LIKE '{$nome_produto}' LIMIT 1";
    $stmt = $conexao->prepare($sql);
    $stmt->execute();

    $num = $stmt->rowCount();

    if($num == 1)
    {
        if($quantidade <= 0 || $quantidade > 20)
        {
            header('Location: produtos.php?acao=quantidadeinvalida&nome_produto=' . $nome_produto);
        }
        else if(!isset($_SESSION['carrinho']))
        {
            $_SESSION['carrinho'] = array();
        }
        if(isset($_SESSION['carrinho']))
        {
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
                extract($row);
                $colunas = array
                (
                    'id_produto_sessao' => $id_produto_sessao,
                    'id_produto' => $id_produto,
                    'nome_produto' => $nome_produto,
                    'preco_produto' => $preco_produto,
                    'quantidade' => $quantidade
                );
            }
            $_SESSION['carrinho'][$id_produto_sessao] = $colunas;
            header('Location: produtos.php?acao=adicionado&nome_produto=' . $nome_produto);
        }
    }   
    else
    {
        redirecionar_para("produtos.php");
    }
}

Note that the reported amount is obtained with the jQuery and passed to the SESSION. I think I’ll have to do something similar to get the data on checkboxes selected, but I have no idea how to do it. I would also put the code in the file cart php. and whose purpose is to display the data present in SESSION cart, but this will leave the question too extensive. I think I should first be able to store the data of these checkboxes. The task of displaying them afterwards should not be so difficult. But back to the problem in question, how to get the values of each of the checkboxes selected previously and also insert them in this SESSION? How to implement this in my system?

  • Do you want something like that? https://jsfiddle.net/724xyyq4/ (Of course, it’s not exactly how you need it... but the idea of taking the checkbox is the same... just edit for your need)

  • @Rafaelwithoeft Thanks for the comment! Yes, it’s more or less that. But I need to specify the prices of each of the additions and multiply them by the quantity informed. In the cart you can enter something like "Product: Pizza, Increments: 2xQueijo, 1xAlho, total: R$(value of the sum of the prices of the increments multiplied by the quantity of each one)"

2 answers

1

Changing HTML makes things a little easier. Changes:

<td>
    <input type='checkbox' name='acr[0]' value='Queijo'/>Queijo - R&#36;2,00 <input type='number' name='quantidade_acr[0]' value='1' min='1' max='5'/><br/>
    <input type='checkbox' name='acr[1]' value='Alho'/>Alho - R&#36;0,50 <input type='number' name='quantidade_acr[1]' value='1' min='1' max='5'/><br/>
    <input type='checkbox' name='acr[2]' value='Oregano'/>Orégano - R&#36;0,50 <input type='number' name='quantidade_acr[2]' value='1' min='1' max='5'/><br/>
</td>

for:

<td classe="acr">
   <input type='checkbox' name='acr[]' value='{"tipo": "Queijo", "preco": 2.0}'/>Queijo - R&#36;2,00 <input type='number' name='quantidade_acr[0]' value='1' min='1' max='5'/><br/>
   etc...

So at the value of those checkboxes you already have the price and you have a class with that td.

Then you can do so to pass it to a Javascript:

var dados = $('.acr input[type=checkbox]:checked').map(function (i) {
    var data = JSON.parse(this.value);
    var qtd = this.checked ? parseInt($(this).next('input').val(), 10) : 0;
    var preco = data.preco;
    var toString = {
        tipo: data.tipo,
        preco: data.preco,
        qdt: qtd,
        total: qtd * data.preco
    };
    var obj = {};
    obj['acr_' + i] = encodeURIComponent(JSON.stringify(toString));
    return obj;
});

var queryString = dados.map(function () {
    return $.param(this, true)
}).get().join('&');

This will create an array dados with objects with type, price, Qtd and total. Then convert all this information numa _query string_, I see you use in your code. So you can join what’s in that variable queryString to the GET you do when you have window.location.href = ... remember to join & between each part of that url.

If you do with AJAX you can do so, within the function that starts sending to the server:

var obj = {};
var dados = $('.acr input[type=checkbox]:checked').each(function (i) {
    var data = JSON.parse(this.value);
    var qtd = this.checked ? parseInt($(this).next('input').val(), 10) : 0;
    var preco = data.preco;
    var dados = {
        tipo: data.tipo,
        preco: data.preco,
        qdt: qtd,
        total: qtd * data.preco
    };
    obj['acr_' + i] = dados;
});
$.post(url, obj, function (res) {
    console.log(res);
});

If you have problems recovering this in PHP puts another question that we can help more.

jsFiddle: https://jsfiddle.net/Lubvpnz5/

  • Thank you very much for the answer, Sergio! I am studying your code, but first could you clarify a question? How JS is client-side can the user be able to edit the price of the addition? For example, <input type='checkbox' name='acr[]' value='{"tipo": "Queijo", "preco": 2.0}'/>Queijo - R&#36;2,00 <input type='number' name='quantidade_acr[0]' value='1' min='1' max='5'/><br/> Getting the price from the JS is safe?

  • @M.Victor that’s a risk yes. But I see that in your code you are using query string, you should use POST. Using POST was the best, and you can use the HTML I suggested above, and do the processing in PHP.

  • The problem with using POST is that, as you can see, there are several forms with the add class. Use jQuery to get the values closest to each form with this class and pass them to the Query String. I don’t know how to do this with POST, since there are several classes with the same name. It would even make it easier if I did everything from the product page instead of going to the add.php file. Do you have any idea how to do that? You can edit your answer with an example of POST that works for me, please?

  • @M.Victor why don’t you do this with AJAX? so you can send via POST. I joined code to send via AJAX.

  • I didn’t understand how to implement this with the other data I get (product id, name, price, etc). No problem for me using Query String because I check if the ID and product name exist in DB there in add.php. Data is only entered into SESSION if it exists. So there in the question I said "Should I have a table in the DB corresponding to the Additions with their proper names and prices?" Because doing by server-side the user has no way to change important data such as price. Would not have to do something like that? Save the names and prices of additions to DB?

  • Sergio, I edited the question. I’m trying to do it the way I told you: I created the table for the additions, with ID, name and price and I made a loop identical to the products to create a checkbox for each addition. I’m stuck now, my current knowledge doesn’t allow me to continue!

Show 1 more comment

1

You can do the following, in your form, put the date-attribute (the parameter you want to capture):

<input type='checkbox' name='acr[0]' data-id="1" data-valor="2.00" value='Queijo'/>Queijo - R&#36;2,00 <input type='number' name='quantidade_acr[0]' value='1' step="1" min='1' max='5'/><br/>
                <input type='checkbox' data-id="2" data-valor="0.50" name='acr[1]' value='Alho'/>Alho - R&#36;0,50 <input type='number' name='quantidade_acr[1]' value='1' step="1" min='1' max='5'/><br/>
                <input type='checkbox' data-id="3" data-valor="0.50" name='acr[2]' value='Oregano'/>Orégano - R&#36;0,50 <input type='number' name='quantidade_acr[2]' value='1'step="1" min='1' max='5'/><br/>

<button id="salvar">Salva</button>

Then create the jquery method to save the data:

$(document).ready(function(){
    $('#salvar').on('click', function() {
        var list = [];
         $('[name*="acr"]:checked').each(function(key) {

             var qtde = $('[name*="quantidade_acr['+key+']"]').val();
             var produto = $(this).val();
             var id = $(this).data('id');
             var valor = $(this).data('valor');
             var total = qtde * valor;
            list[key] = {
                          produto: produto,
                          quantidade: qtde,
                          id: id,
                          valor: valor,
                          total_valor: total
                         };

           });
          /* aqui eu dei uma saída em HTML
             do JSON apenas para exibir, o
             ideal é que você envie esse
             array para o seu método post. */
           alert(JSON.stringify(list));

    });
});

Here is the example: https://jsfiddle.net/ivanferrer/kumyaj8g/

Here a more complex example: http://jsfiddle.net/ivanferrer/nq9Lts0f/1/

Browser other questions tagged

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