How i add a function to each row selected

How i add a function to each row selected

alfasino9alfasino9 Posts: 31Questions: 5Answers: 0

Hello,

I have a datatable working here -> http://comparador.masqueunaweb.com/buscador3.php

I need when we click on the button "Actualizar" start a function for this row.

The function i wan't to add is this one:

function descontarPrecio(data.id, data.precio, data.precioComp1, data.precioComp2, data.precioComp3){

$precioMin = min(data.precioComp1, data.precioComp2, data.precioComp3);
  $precioNuevo = $precioMin;
       --$precioNuevo;
    echo $precioNuevo;

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "UPDATE productos SET precio = '$precioNuevo' WHERE id = '$idProducto'";

print ("<p> $sql </p>");

if ($conn->query($sql) === TRUE) {
    echo "Precio actualizado!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
  

        }

  descontarPrecio ();

That is not working, i have addapted to what i wan't,

Any help would be appreciate!

This question has an accepted answers - jump to answer

Answers

  • alfasino9alfasino9 Posts: 31Questions: 5Answers: 0

    No one? :s

  • alfasino9alfasino9 Posts: 31Questions: 5Answers: 0

    Any help?? I reallyhave no idea of how to do this.

    Thank you!

  • crush123crush123 Posts: 417Questions: 126Answers: 18

    I am assuming you are using the function to compare the values in your table and update one of the fields with the lowest one ?

    could you not use the id of the currently highlighted row then pass this value into ajax to do the database update ?

    something like

    {
    
            extend: 'selected',
            text: 'Actualizar',
            action: function ( e, dt, button, config ) {
                rowid = table.row( { selected: true } ).id()
                rowid = rowid.substr(4);
                console.log( rowid );
    
                $.ajax ({
              url: '/ajax/priceupdate.php',
              data: {
                  id: rowid         
                  },
              method :'POST',
              dataType: 'json',
    
              success: function(data) {
                       console.log('Success!', data);
    
                    },
            error: function(e) {
                        console.log('Error!', e);
            }
        } );    
    
    
            }
        }
    
  • alfasino9alfasino9 Posts: 31Questions: 5Answers: 0

    Hello @crush123 , that's a good starting point.

    Well, i have added to my datatable:

    `extend: 'selected',
    text: 'Actualizar',
    action: function ( e, dt, button, config ) {
    rowid = table.row( { selected: true } ).id()
    rowid = rowid.substr(4);
    console.log( rowid );

            $.ajax ({
          url: 'priceupdate.php',
          data: {
              id: rowid        
              },
          method :'POST',
          dataType: 'json',
    
          success: function(data) {
                   console.log('Success!', data);
    
                },
        error: function(e) {
                    console.log('Error!', e);
        }
    } );   
    
    
        }
    }`
    

    And i have created one php file named priceupdate.php with the following code:

    <?php
    
    function descontarPrecio(data.id, data.precio, data.precioComp1, data.precioComp2, data.precioComp3){
     
    $precioMin = min(data.precioComp1, data.precioComp2, data.precioComp3);
      $precioNuevo = $precioMin;
           --$precioNuevo;
        echo $precioNuevo;
     
    $servername = "localhost";
    $username = "";
    $password = "";
    $dbname = "";
     
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
     
    $sql = "UPDATE productos SET precio = '$precioNuevo' WHERE id = '$idProducto'";
     
    print ("<p> $sql </p>");
     
    if ($conn->query($sql) === TRUE) {
        echo "Precio actualizado!";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
     
    $conn->close();
       
     
            }
     
      descontarPrecio ();
      
     ?>
    

    If i click on the Actualizar button, that's the error shown in the console:

    Uncaught ReferenceError: table is not defined

    I pretty sure my priceupdate.php is not right done. But i think is something missing with the rowid = table.row( { selected: true } ).id() , no?

    Let me know and thank you for your help!

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited October 2017

    in your script, change

                $('#productos').DataTable({
                dom: "Bfrtip", ................
    

    to

           table =  $('#productos').DataTable({
                dom: "Bfrtip",  .............
    

    The ajax was just an idea to get you started, it is a different approach to what you were using,

    in your ajax page, you need to use the row id passed from the datatable as your filter.

    you also need to pass in the value to the field you are updating

    you should return something from the ajax page to the calling function so you know the update has been successful

    ...there may be an easier way for you.

    have you seen this thread ?

    https://editor.datatables.net/examples/api/triggerButton

  • alfasino9alfasino9 Posts: 31Questions: 5Answers: 0

    Hello,

    Ok now the Uncaught error is clear.

    Ok i think i'm very newbie for that, hahah

    I have no idea how my priceupdate.php have to look.

    Can you give me some hints of how the priceupdate.php has to be?

    Let me know, and really appreciate all your help and hints.

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited October 2017 Answer ✓

    actually i think my second suggestion is better

    assuming you are setting the value of column precio from the minimum values of columns precioComp1, precioComp2 and precioComp3

    {
                extend: "selectedSingle",
                text: "Actualizar",
                action: function ( e, dt, node, config ) {
                    // Immediately set precio to the minvalue and submit
                        selectedrow = table.row( { selected: true } ).data();
                        minvalue = Math.min(selectedrow.precioComp1,selectedrow.precioComp2,selectedrow.precioComp3);
                        //console.log(minvalue);
                    editor
                        .edit( table.row( { selected: true } ).index(), false )
                        .set( 'precio', (minvalue ))
                        .submit();
                }
            }
    
  • alfasino9alfasino9 Posts: 31Questions: 5Answers: 0

    You really rocks @crush123 !!!

    Works!!

    And now, if i wan't create another button to update ALL the prices ? It's the same, but without the id.row?

    Really thank you!!!

  • crush123crush123 Posts: 417Questions: 126Answers: 18

    if you wanted to do it with a button, you would most probably need to loop through the whole array, passing in the id sequentially.

    don't know if that is the best way of doing it

  • alfasino9alfasino9 Posts: 31Questions: 5Answers: 0

    Okay, thank you @crush123

    Best regards

  • crush123crush123 Posts: 417Questions: 126Answers: 18

    Personally, this is where I would use the Ajax call, you have no parameters to pass through, so a simple update query would do it

  • alfasino9alfasino9 Posts: 31Questions: 5Answers: 0

    Hello, i have now finally not used the editor function.

    Now i only use the datatable function.

    Is there any way to do the same as mentioned in the correct answer, but without the editor function?

    With a simple mysql query?

    Really appreciate any help.

    Regards

  • allanallan Posts: 62,211Questions: 1Answers: 10,205 Site admin

    Do you want to set them all to be the same price? And you want that price to be a value that is input? If so, you could just use something like:

                    editor
                        .edit( table.rows( { selected: true } ).index(), false );
    

    and let the user enter the price. Note the use of rows() to allow for multiple rows.

    Allan

  • alfasino9alfasino9 Posts: 31Questions: 5Answers: 0
    edited December 2017

    I dont have the editor plugin now.. :(

    I only need to update (with --minvalue) a mysql cell based on a condition

    For that, with the editor plugin and the help of @crush123 i have succesfully done that with the correct answer.

    Now, i need to do the same, but without the editor plugin. Is it possible?

    Thank you for your help

  • allanallan Posts: 62,211Questions: 1Answers: 10,205 Site admin

    I'm certain it is, but that would be outside of the scope of the support that I can provide.

    Allan

This discussion has been closed.