skip to Main Content

I am trying to create editable table, I am using ajax request for the same by following a tutorial over youtube, but the ajax request to save the changes after editing the table seems to fail, please suggest me the possible mistake that is causing the error "Not saved".
Main page code

 <script type='text/javascript'>
$(document).ready(function(){
  
 // Show Input element
 $('.edit').click(function(){
  $('.txtedit').hide();
  $(this).next('.txtedit').show().focus();
  $(this).hide();
 });
 
 // Save data
 $(".txtedit").focusout(function(){
   
  // Get edit id, field name and value
  var id = this.id;
  var split_id = id.split("_");
  var field_name = split_id[0];
  var edit_id = split_id[1];
  var value = $(this).val();
   
  // Hide Input element
  $(this).hide();
 
  // Hide and Change Text of the container with input elmeent
  $(this).prev('.edit').show();
  $(this).prev('.edit').text(value);
 
  $.ajax({
  url: 'update.php',
  method: 'POST',
  data: { field:field_name, value:value, id:edit_id },
  success:function(response){
    if(response == "success"){ 
      console.log('Saving successfully'); 
    }else{ 
      console.log("Not saving.");  
    }
  },
  error: function(xhr, status, error) {
    console.log("Error: " + xhr.responseText);
  }
});
  
 });
 
});
</script>

</head>
<body>
<div id="bgn"></div>
<div id="titlebar">
  <h1 id="pageTitle">PROJECT MANAGEMENT SYSTEM</h1>
  <div id="bg1"></div>

<div id="menu">
  <ul id="menuitems">
    <li>
      <div class="menu-item">
        <span class="icon-signini" onclick="signOut()"></span>
        <span class="item" onclick="signOut()">Sign Out</span>
      </div>
    </li>

    <li>
      <div class="menu-item" id="masterdata">
          <span class="icon-dashbi"></span>
          <span class="item">Master Data</span>
        <!-- Submenu -->
        <ul id="projectSubMenu" class="submenu" onclick="department_table()">
          <li><span>Department List</span></li>
          <div class="departable">


</div>
          <li><span onclick="project_table()">Projects List</span></li>
        </ul>
      </div>
    </li>

    <li>
      <div class="menu-item">
        <span class="icon-transi"></span>
        <span class="item">Transactions</span>
        <!-- Submenu -->
      </div>
    </li>

    
<li>
      <div class="menu-item">
        <div class="project">
          <span class="icon-requestpi"></span>
          <span class="item" onmouseover="toggleSubmenu('projectSubMenu')">Reports</span>
        <!-- Submenu -->
        <ul id="projectSubMenu" class="submenu">
        </ul>
      </div>
    </li>

  </ul>
</div>
</div>


<div id= "tablePane"  style="display: none;">
<div id= departtableTitle>
  <h1>DEPARTMENT TABLE</h1>
  </div>
  <div id= buttons>
  <button class="btn" type="button" name="add">Add</button> 
  <button class="btn" type="button" name="save" onclick="save">Delete</button>
  <button class="btn" type="button" name="save">Edit</button>
  <button class="btn" type="button" name="save">Save</button>
  </div>
<div class="tableContainer">
    <table class="departable" id="department_table">
    <thead>
        <th>Sr No.</th>
        <th>Name</th>
        <th>Username</th>
        <th>Email</th>
        <th>Department</th>
</thead>

<tbody>
        <?php
        include('db.php');

        // Create connection
        $conn = new mysqli($hostname, $user_name, $pass_word, $database);
        
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        
        $query_departid= " SELECT `department` FROM `department id`";
        $query_departable= " SELECT `id`,`name`,`username` ,`email`, `department id` FROM `users`order by `id`";
        $result_departable= mysqli_query($conn,$query_departable);

         $counter = 1; // Initialize counter
         while($row_departatble = mysqli_fetch_assoc($result_departable))
            {
          ?>
            <tr>  
            <td><?php echo $counter; ?></td>
            <td>
            <div class='edit' > <?php echo $row_departatble['name'];?></div> 
            <input type='text' class='txtedit' value='<?php echo $row_departatble['name'];?>' id='name_<?php echo $row_departatble['id'];?>' >
            </td>
            <td>
            <div class='edit' > <?php echo $row_departatble['username'];?></div> 
            <input type='text' class='txtedit' value='<?php echo $row_departatble['username'];?>' id='username_<?php echo $row_departatble['id'];?>' >
            </td>
            <td>
            <div class='edit' > <?php echo $row_departatble['email'];?></div> 
            <input type='text' class='txtedit' value='<?php echo $row_departatble['email'];?>' id='email_<?php echo $row_departatble['id'];?>' >
            </td>
            <td>
            <div class='edit' > <?php echo $row_departatble['department id'];?></div> 
            <input type='text' class='txtedit' value='<?php echo $row_departatble['department id'];?>' id='department_<?php echo $row_departatble['id'];?>' >
            <?php echo $row_departatble['department id'];?></td>
            </tr>
            <?php
            }
            $count ++;
            ?>

</tbody>          
    </table>
          </div> 
</div>

update.php

<?php
include('db.php');
if(isset($_POST['field']) && isset($_POST['value']) && isset($_POST['id'])){
   $field = $_POST['field'];
   $value = $_POST['value'];
   $editid = $_POST['id'];
 
    $sql = "UPDATE user SET ".$field."='".$value."' WHERE id = $editid"; 
    $update = $conn->query($sql); 
 
       echo "success";
}else{
   echo "fail";
}
exit;
?>

db.php


<?php
// Database configuration
$hostname = "localhost"; // Replace with your host name
$user_name = "root"; // Replace with your database username
$pass_word = ""; // Replace with your database password
$database = "project_ms"; // Replace with your database name

// Establishing the database connection
$conn = mysqli_connect($hostname, $user_name, $pass_word, $database);

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}
?>

browser console

2

Answers


  1. Chosen as BEST ANSWER

    There was an error in the syntax of the SQL statement due to which it was not functioning correctly, thankyou all for the suggestions!


  2. On the client JS side, you’re checking for response == "success", but on the backend PHP side, you’re outputting echo 1.

    There are two solutions:

    1. Change the JS condition to if(response == "1") instead of if(response == "success")

    or

    1. Change the PHP response to echo "success"; instead of echo 1;
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search