0

I am having the following problem.

I am setting up a panel for the website where I can upload new products, delete products and edit product values. The panel works with ajax and php. The problem I have is with the section to edit products.

I need the editor(individual for each product) to open in a modal with all the product values so that I can edit manually as needed. The part of opening it in a modal is already solved.

When pressing the edit button, the modal opens, and the inputs are filled with the values of the product to edit, stored in the database, but there are inputs that are empty. The values arrive without any problem, but the input does not show them. Here I share with you the codes:

Product Table:

  <tr>
   <th>Seleccionar</th>
   <th>Código de Producto</th>
   <th>Imágen</th>
   <th>Nombre de Producto</th>
   <th>Categoría</th>
   <th>Destacado</th>
   <th>Activo</th>
   <th>Editar</th>
   <th>Borrar</th>
  </tr>
  <tr>
   <td>
    <form action="" method="post">
      <input type="checkbox" name="records[]" value="'.$row["image_id"].'">
    </form>
   </td>
   <td>'.$row["codigo"].'</td>
   <td><img src="images/productos/'.$row["image_name"].'" class="img-thumbnail" width="100" height="100" /></td>
   <td>'.$row["nombre_producto"].'</td>
   <td>'.$row["category"].'</td>
   <td>'.$row["destacado"].'</td>
   <td>'.$row["activo"].'</td>
   <td><button type="button" class="btn btn-warning btn-xs edit" id="'.$row["image_id"].'">Editar</button></td>
   <td><button type="button" class="btn btn-danger btn-xs delete" id="'.$row["image_id"].'" data-image_name="'.$row["image_name"].'">Borrar</button></td>
  </tr>
</table>

Modal that appears when we press "Edit" on any product in the table:

    <!-- inicio modal -->
    <div class="modal fade" id="imageModal" role="dialog">
     <div class="modal-dialog">
      <div class="modal-content">
       <form method="POST" id="edit_image_form">
            <div class="modal-header">
                   <button type="button" class="close" data-dismiss="modal">&times;</button>
                   <h4 class="modal-title">Editar Detalles de Producto</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                   <label>ID</label>
                   <input type="text" name="image_id" id="image_id" class="form-control"/>
                   <label>Nombre de Imágen</label>
                   <input type="text" name="image_name" id="image_name" class="form-control"/>
                   <label>Descripción</label>
                   <input type="text" name="image_description" id="image_description" class="form-control"/>
                   <label>Nombre de Producto</label>
                   <input type="text" name="product_name" id="product_name" class="form-control"/>
                   <label>Categoría</label>
                   <input type="text" name="category" id="category" class="form-control"/>
                   <label>Código de Producto</label>
                   <input type="text" name="product_code" id="product_code" class="form-control"/>
                   <label>Diametro</label>
                   <input type="text" name="diametro" id="diametro" class="form-control"/>
                   <label>Peso</label>
                   <input type="text" name="peso" id="peso" class="form-control"/>
                   <label>Tipo</label>
                   <input type="text" name="tipo" id="tipo" class="form-control"/>
                   <label>Comensales</label>
                   <input type="text" name="comensales" id="comensales" class="form-control"/>
                   <label>Capacidad</label>
                   <input type="text" name="capacidad" id="capacidad" class="form-control"/>
                   <label>Recubrimiento Exterior</label>
                   <input type="text" name="recub_ext" id="recub_ext" class="form-control"/>
                   <label>Recubrimiento Interior</label>
                   <input type="text" name="recub_int" id="recub_int" class="form-control"/>
                   <label>Origen</label>
                   <input type="text" name="origen" id="origen" class="form-control"/>
                </div>
            </div>
            <div class="modal-footer">
                 <input type="hidden" name="image_id" id="image_id" value="" />
                 <input type="submit" name="submit" class="btn btn-info" value="Editar" />
                 <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
            </div>
       </form>
      </div>
     </div>
    </div> 
    <!-- fin modal -->

Ajax code that fills the input of the modal:

<!-- editar producto: leer valores -->
     $(document).on('click', '.edit', function(){
      var image_id = $(this).attr("id");
      $.ajax({
       url:"edit.php",
       method:"post",
       data:{image_id:image_id},
       dataType:"json",
       success:function(data)
       {
        
        $('#imageModal').modal('show');

        $('#image_id').val(image_id);  //ok
        $('#image_name').val(data.image_name);  //ok
        $('#image_description').val(data.image_description);  //ok
        $('#category').val(data.category);  //ok
        $('#tipo').val(data.tipo);  //ok
        $('#capacidad').val(data.capacidad);  //ok
        $('#recub_ext').val(data.recub_ext);  //ok
        $('#recub_int').val(data.recub_int);  //ok
        $('#origen').val(data.origen);  //ok
        
        
        alert(data.product_name);  //value ok-debug
        alert(data.product_code);  //value ok-debug
        alert(data.peso);  //value ok-debug
        alert(data.comensales);  //value ok-debug
        

        <!-- no funciona-->
        $('#product_name').val(data.product_name);
        $('#product_code').val(data.product_code);
        $('#peso').val(data.peso);
        $('#diametro').val(data.diametro);
        $('#comensales').val(data.comensales);
        <!-- no funciona-->
       }
      });
     });

Edit.php code for ajax function:

<?php
include('database_connection.php');

$query = "
SELECT * FROM tbl_image 
WHERE image_id = '".$_POST["image_id"]."'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

foreach($result as $row)
{
 $output['image_name'] = $row["image_name"];
 $output['image_description'] = $row["image_description"];
 $output['product_name'] = $row["nombre_producto"];
 $output['category'] = $row["category"];
 $output['product_code'] = $row["codigo"];
 $output['tipo'] = $row["tipo"];
 $output['diametro'] = $row["diametro"];
 $output['comensales'] = $row["comensales"];
 $output['capacidad'] = $row["capacidad"];
 $output['peso'] = $row["peso"];
 $output['recub_ext'] = $row["recub_ext"];
 $output['recub_int'] = $row["recub_int"];
 $output['origen'] = $row["origen"];
 
}


echo json_encode($output);

?>

Here you have php query result (my debug):


print_r($row)

Array ( [image_id] => 1030 [0] => 1030 [image_name] => f4-2145269539.png [1] => f4-2145269539.png [image_description] => probando la descripcion [2] => probando la descripcion [category] => aqua [3] => aqua [codigo] => 387535555 [4] => 387535555 [nombre_producto] => Cacerola 20cm [5] => Cacerola 20cm [tipo] => cacerola [6] => cacerola [diametro] => 20 [7] => 20 [capacidad] => 2,5 [8] => 2,5 [comensales] => 3 [9] => 3 [recub_ext] => esmalte vitroporcelanizado [10] => esmalte vitroporcelanizado [recub_int] => antiadherente [11] => antiadherente [destacado] => 0 [12] => 0 [activo] => 0 [13] => 0 [medidas] => [14] => [origen] => nacional [15] => nacional [peso] => 4 [16] => 4 ) 


echo json_encode($output);

{"image_name":"f4-2145269539.png","image_description":"probando la descripcion","product_name":"Cacerola 20cm","category":"aqua","product_code":"387535555","tipo":"cacerola","diametro":"20","comensales":"3","capacidad":"2,5","peso":"4","recub_ext":"esmalte vitroporcelanizado","recub_int":"antiadherente","origen":"nacional"}

And finally a picture so that you can understand how it looks like: enter image description here

I hope you can help me because I really can't find the error. Thank you all very much!

I try doing this, and it works perfectly. It shows product_code value on input id="origen".

$('#origen').val(data.product_code); 

Regards.

juanpb12
  • 125
  • 1
  • 9
  • 1
    you should learn to target the inputs without using ids, i.e get the unique parent as a scope, which you might have already for .close(), i.e let imageModal = $('#imageModal') then do `imageModal.find('input[name="peso"]').val(data.peso)`, heavily targeting with id's is prone to breaking – Lawrence Cherone Aug 06 '21 at 01:24
  • 2
    also use `fetchAll(PDO::FETCH_ASSOC)`, if your only using column names, plus, `... WHERE image_id = '".$_POST["image_id"]."'` is open to sql injection – Lawrence Cherone Aug 06 '21 at 01:27
  • @LawrenceCherone thanks a lot you solved my problem. I'm beginner and I don't knew this method. But I Didn't understand what do you mean about sql injection. I'm going to see documentation about it. Thanks Again. – juanpb12 Aug 06 '21 at 01:43
  • solve was using: `imageModal = $('#imageModal'); ` and `imageModal.find('input[name="product_code"]').val(data.product_code); ` – juanpb12 Aug 06 '21 at 01:46
  • We do not mark Q&A pages as resolved by editing `SOLVED` into the title. Please take the [tour]. You should "alias" the SELECT columns in your sql, so that you don't have to change the keys in php before returning the json payload. You should read about prepared statement for injection security and stability. Feed `fetchAll()` directly into your echo'ed json call. ...wait a sec, why call `fetchAll()` to get one row of data??? Just use `fetch()` – mickmackusa Aug 06 '21 at 01:54
  • If you don't already know, you can relate `label` tags to specific fields by giving them a `for` attribute that matches the field's `id` attribute. – mickmackusa Aug 06 '21 at 02:34

0 Answers0