Sophia_1 0 Junior Poster in Training

Hi, tried to save the textbox color T11 based on rating value but unable to save. For example, if the rating=Good, the textbox color T11 =green. But when i click save, T11 color goes back to black and select option goes back to "Please select an option". T11 textbox color can be save before i include the file upload function, but after putting in the file upload and display codes the T11 textbox color goes cannot be save . Please advise. Thanks.

            <div class="text"> 
                <label for="Attachment">Forms:  </label> 
            <a href="<?php echo $row['progressid'] ?>" target="popup" onclick="window.open('<?php echo $row['progressid'] ?>','name','width=600,height=400')">Upload file</a>
            <br>
            <?php
            $host = 'localhost';  
            $user = 'user';  
            $pass = '';  
            $dbname = 'p';  
            $conn = mysqli_connect($host, $user, $pass,$dbname);  
            if(!$conn){  
              die('Could not connect: '.mysqli_connect_error());  
            }  
            //echo 'Connected successfully<br/>';  

            $progressid=$row['progressid'];
            $sql = "SELECT * FROM file WHERE  progressid='".$progressid."'";  
            $retval=mysqli_query($conn, $sql);  

            if(mysqli_num_rows($retval) > 0){  
             while($row = mysqli_fetch_assoc($retval)){  
              $id=$row['id'];
             } //end of while  
             echo $id;
             } else{  
            echo "0 results";  
            }  
            mysqli_close($conn); 
            ?>  
            <a href="<?php echo $id ?> " target="popup" onclick="window.open('<?php echo $id ?>','name','width=600,height=400')">View file</a>
            </div> 
            <p><b>2.Rating</b></p>
            <script type="text/javascript">
              $('#rating').change(function(){
                var color = $('#rating').val();
                $('#T11').css('background-color', color);
                });
            var colo = '';
            function submit_color() {
                var col = $('#T11').css('background-color');
                hexc(col);
                $.ajax({
                   url: 'progress.php', 
                    type: 'post',
                    data: {"T11" : colo},
                    success: function(res){
                        alert(res)
                    },
                });
            }
            function hexc(colorval) {
                var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
                delete(parts[0]);
                for (var i = 1; i <= 3; ++i) {
                    parts[i] = parseInt(parts[i]).toString(16);
                    if (parts[i].length == 1) parts[i] = '0' + parts[i];
                }
                colo = '#' + parts.join('');
            }
            </script>    
            <script>
            function ocalculateText(el) {
              var form = el.form;
              var idx = form.rating.selectedIndex;
              if (idx <= 0) {
                form.reset();
                return;
              }
              if (form.rating.value == "Good") {
                  form.T11.value = "#008000";
              } else if (form.rating.value == "Satisfactory") {
                form.T11.value = "#9ACD32";
              } 
              }
            </script>        
                <div class="text" style="float:left;"> 
                <label for="rating">Rating: </label> 
                <select name="rating" id="rating" onchange="ocalculateText(this)" value="<?php echo $row['rating']; ?>"> 
                    <option selected>Please select an option</option>                           
                    <option value=Good <?php if($row['rating']=='Good') { echo "selected"; }?>>Good</option>
                    <option value=Satisfactory <?php if($row['rating']=='Satisfactory') { echo "selected"; }?>>Satisfactory</option>
                    </select> 
                </div> 
            <div class="text" style="float:left;"> 
            <input type="color"  name="T11" id="T11"  value="<?php echo $row['T11']; ?>"/>

Dani AI

Generated

As describes, the form values (rating and the color input) look correct before the file-upload block but revert after saving. The most common and immediate cause for that exact symptom is overwriting the main row variable when you run a nested query. The inner mysqli_fetch_assoc() loop appears to reuse $row, so by the time you echo $row['rating'] and $row['T11'] the original record has been clobbered and the form falls back to defaults.

Fixes to apply (in order):

  • Stop reusing $row in the file query. Fetch into a different variable (for example $fileRow or $files) or store the main record into another variable before the nested query. That will preserve the values you intend to echo into the form.
  • Simplify the client->server flow for color: read the color input value directly ($('#T11').val() returns a hex like #008000) instead of reading computed CSS and converting RGB. Send that hex to the server and update the DB. This avoids fragile color conversions.
  • Remove the unnecessary value="..." on the <select> tag and rely on the PHP-generated selected attribute on the correct <option>. Also avoid calling form.reset() in the select handler unless you explicitly want to clear every field.

Minimal examples (illustrative, not copies of your posted blocks):

// keep the main row intact
$mainRow = $row; // copy outer record if needed
$progressid = $mainRow['progressid'];

$result = mysqli_query($conn, $sql);
while ($fileRow = mysqli_fetch_assoc($result)) {
    $fileId = $fileRow['id'];
}
echo $fileId;
// submit the hex value directly
function submitColor(progressId) {
  var hex = $('#T11').val(); // "#008000"
  $.post('progress.php', { T11: hex, progressid: progressId }, function(res){
    console.log(res);
  });
}

Debug checklist:

  • Open DevTools Network tab and confirm the POST contains the hex and server returns success.
  • Check the DB row to ensure T11 was updated.
  • Look for PHP notices about undefined indices (they point to overwritten variables).
  • Use prepared statements for the update to avoid SQL errors and injection.

For reference: input[type=color] behavior and form.reset() details are documented at MDN:
input type=color and HTMLFormElement.reset().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.