0

My problem is that I created a cart shop of products that are saved in a database, then I created a while to print the info of the product (name, genre, price) and next of them the quantity of products one want to buy.

The problem is that only reads one of the multiple inputs created and calculate with that quantity instead of every one the created ones. So I am glad if you can help my in fix the part of the code that is causing the problem.

Sorry if something is unclear, it is my first post here.

Here are the codes.

The PHP file that prints the info:

<tbody>
<tr>
    <?php
    $conexion  = mysqli_connect("localhost", "root", "", "llanoponte");
    $sql       = "SELECT * FROM libros";
    $resultado = $conexion->query($sql);
    $x         = 0;

    if ($resultado->num_rows > 0) {
        while ($row = $resultado->fetch_assoc()) {
            $valor = $row['Precio'];
            echo "<td>", $row['Titulo'], "</td>
                    <td>", $row['Autor'], "</td>
                    <td>", $row['Genero'], "</td>
                    <td>", $valor, " €", "</td>
                    <td>", "<input type='number' name='cantidad' class='cantidad' value='0' id='<?php echo $x ?>'>", "</td>
                </tr>";
            $x++;
        }
    } else {
        echo "Sin resultados";
    }
    
    $conexion->close();
    ?>
</tr>
</tbody>

Here is the button to call the function

<input type="button" name="actualizar" class="calcular" onclick="Datos()" id="boton1" value="Calcular">

The script that sends the inserted quantity to the PHP file that makes the operation:

function Datos() {

    v1 = $("input[name='cantidad']").val();

    $.ajax({
        url: 'total.php',
        type: 'post',
        data: {cantidad: v1},
        success: function (respuesta) {
            $('#resultados').html(respuesta);
        }
    })
}

The PHP that calculates the total and return the value to the principal:

include('conexiones.php');

$multi1    = $_POST['cantidad'];
$conexion  = mysqli_connect("localhost", "root", "", "llanoponte");
$sql       = "SELECT * FROM libros";
$resultado = $conexion->query($sql);

if ($resultado->num_rows > 0) {
    $total    = 0;

    while ($row = $resultado->fetch_assoc()) {
        $total = ($row['Precio'] * $multi1) + $total;
    }

    echo '<p>', $total, ' € ', '</p>';

} else {
    echo 'Sin resultados';
}

$conexion->close();

And this is where the total of price should appear

<div class="texto2">
            <h1>Total</h1>
            <div id="resultados">
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
            </div>
        </div

I tried change the IDs to an element whose value will increase by every loop of the while loop but then I faced with the obstacle of send the inputs and their values to the other PHP through the script. And even trying to change from obtaining the value from element with certain id to name, it still captures the value of the first input created and not the rest.

Paul
  • 1
  • 2
  • How is `Datos()` called? Is the `$id = ` at the start of it just a typo here on SO, or is that your real code? `$("input[name='cantidad']")` will match every input on the page, and `.val()` of that set [will only return the value of the first one](https://api.jquery.com/val/). – Don't Panic Apr 30 '23 at 11:43
  • I already added how is the function Datos() called, and about $id =, it was some code i forgot to delete when i was searching ways to fix my problem. And respect that .val() will return only the value of the first value, any idea about how send/return the value of every input generated? Thanks for reading this. – Paul Apr 30 '23 at 14:10
  • You have quite a few problems at the moment. 1) All your `input`s have the same `name`, which means they will all overwrite each other, and only 1 of them will be POSTed to your back end. You could see this if you `print_r($_POST);` in your PHP. You need to pass the values as an array, and iterate over them, [here's an example](https://stackoverflow.com/questions/3314567/how-to-get-a-form-input-array-into-a-php-array). – Don't Panic May 01 '23 at 06:40
  • 2) Now you have a set of quantity values on the backend, but there is nothing to relate any of those values to any particular item in your DB. You need quantity *and* the product ID that quantity is for. You could either add a hidden input for every quantity input which includes the product ID, or simpler, use the product ID as the input array key ([example](https://stackoverflow.com/questions/4821861/searching-for-array-key-in-post-php)). – Don't Panic May 01 '23 at 06:47
  • 3) You need data from the whole form on the back end, not individual values, so you want to POST the whole form. No need for the `v1` variable in Javascript - [just POST the form](https://stackoverflow.com/questions/15173965/serializing-and-submitting-a-form-with-jquery-and-php). – Don't Panic May 01 '23 at 06:47

1 Answers1

0

I think you have to cycle over the object returned by the $("input[name='cantidad']") selector and put each value into an array to be passed to the ajax call::

let data = [];
$("input[name='cantidad']").each((k, v) => data.push(v.value));

In this other way you can take also the ids:

let data = [];
$("input[name='cantidad']").each((k, v) => {let o = {}; o[v.id] = v.value; data.push(o);});

And I recommend that you assign the primary key of the records to the input ids instead of assigning the $x counter: this way you can multiply the price of each book by the amount of selected books, making an intersection with the selected books and their prices read from DB (using multiple queries or an array comparison)

Pippo
  • 2,173
  • 2
  • 3
  • 16