Остановить обновление страницы после обновления строки до jquery ajax - PullRequest
0 голосов
/ 09 июля 2020

Мои данные успешно обновлены, и после обновления они отображаются в таблице в браузере с обновленной строкой. но проблема в том, что после обновления он перезагружает страницу. пожалуйста, посоветуйте мне, что мне сделать, чтобы моя страница не обновлялась? потому что я использовал ajax jquery для обновления моей строки.

Я использовал функцию перезагрузки страницы в методе ajax success для перезагрузки страницы, но без перезагрузки страницы мои данные не обновляются.

add_user. php


    <?php
    
    $sql="SELECT * from users where role = 'tm'";
    $result=mysqli_query($conn,$sql);
    
    
    ?>
    <div class="container">
        <center>
        <h5 class="card-header info-color white-text text-center py-4"><strong>Users Details</strong> </h5>
        </center> <br/> 
        
        
    
    
    <?php
    if(mysqli_num_rows($result)>0)
    {?>
        <table class="table table-striped" id="example" align="center">
            
                <thead>
                <tr class="justify-content-center">
                    <th style="padding:7px">Name</th>
                    <th style="padding:7px">Email</th>
                    <th style="padding:7px">Position</th>
                    <th style="padding:7px">Action</th>
                    </tr>
                </thead>
            
                <tbody id="myTable">
    <?php
        echo "<tr>";
        
        while($row=mysqli_fetch_assoc($result))
        {
            $id = $row['id'];
            echo "<td style='padding:7px'>".$row["name"]."</td>";
            echo "<td style='padding:7px'>".$row["email"]."</td>";
            echo "<td style='padding:7px'>".$row["position"]."</td>";
            ?>
            <td style='padding:7px'><button class="btn btn-info"  onclick="deleteUser('<?php echo $row['id'];?>')"> <i class="fa fa-trash"></i> DELETE </button> |
            <button class="btn btn-info  edit" value="View Data" edit-id="<?php echo $row['id']; ?>">  <i class="fa fa-pencil"></i> EDIT </button> |        
            <button class="btn btn-info  abc" value="View Data" data-id="<?php echo $row['id']; ?>">  <i class="fa fa-eye"></i> VIEW DATA </button>
    
            </td>
    
    
            <?php echo "</tr>"; 
        } ?>
                </tbody>
    
                
        <?php
         echo "</table>";
         
     }
    else
        {
            echo "No row exists";
        }
    ?>
    </div>
    
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
        
          <!-- Modal content-->
          <div class="modal-content">
            <div class="modal-header">
              
              <h4 class="modal-title"> </h4>
            </div>
            <div id="displaydata">
              
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>
          </div>
          
        </div>
      </div>
    
      <div class="modal fade" id="editmodal" role="dialog">
        <div class="modal-dialog">
        
          <!-- Modal content-->
          <div class="modal-content">
            <div class="modal-header">
              
              <h4 class="modal-title"> Update Details </h4>
            </div>
            <div id="editbody">
            <div class="container">
            <form method="POST" id="editform">
            <div class="form-group">
                <input type="hidden" name="id" value="" id="userid">
                <label>Name</label>
                <input type="text" name="name" class="form-control" id="userName">
            </div>
            <div class="form-group">
            <label>Email</label>
            <input type="email" name="email" class="form-control" id="email" >
            </div>
            <div class="form-group">
            <label>Position</label>
            <input type="text" name="position" class="form-control" id="position" >
            </div>
              <input type="hidden" name="update" value="update" >
            </form>
        </div>
            </div>
            <div class="modal-footer">
            
              
              <input type = "submit" class="btn btn-info  update" name="insert" id="insert" value="Update">
               <!-- <button type="button" class="btn btn-info  update" name="insert" id="insert" onclick="updatedetail()"> Update </button> -->
              <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>
          </div>
          
        </div>
      </div>
    
    <script>
        $(document).ready(function() {
            $('.abc').on('click',function(){
                var dataId = $(this).attr("data-id");
                        $.ajax({
                                method: "POST",
                                url: "single_user.php",
                                // data : $('#displaydata').serialize(),
                                dataType: "html",
                                data:{ dataId : dataId}, 
                                success: function(response)
                                {
                                $('#displaydata').html(response);
                                $('#myModal').modal('show');        
                                }           
                                });
                            });
    
            $('.edit').on('click',function(){
                    var editId = $(this).attr("edit-id");               
                        $.ajax({
                                 method: "POST",
                                 url: "edit_user.php",                           
                                 data: {editId: editId},
                                 dataType: "json",
                                 success: function(response)
                                 {  
                                     $('#userid').val(response.id); 
                                     $('#userName').val(response.name);
                                     $('#email').val(response.email);
                                     $('#position').val(response.position);
                                     $("#editmodal").modal('show');                                 
                                 }                           
                                 });
                            });
    
            $('.update').on('click',function(){
                $.ajax({
                        method:"POST",
                        url: "edit_user.php",
                        data:$('#editform').serialize(), 
                        dataType: 'json',
                        success: function(response)
                        {
                            $('#userName').val(response.data.name);
                            $('#email').val(response.data.email);
                            $('#position').val(response.data.position);
                            $('#editmodal').modal('hide');
                            location.reload(true);
                        }
                            });
                        });
    
                        $('#example').DataTable({
                            scrollY: 370,
                            "columnDefs" : [{
                                "targets" : [3],
                                "orderable" : false,
                                "searchable" :false
                            }]
                        });
                        });
    
        function deleteUser($id) {
        var ask = window.confirm("Are you sure you want to delete?");
        if (ask) {
    
            window.location.href = "del_user.php?id="+$id;
    
        }
    }
    </script>

edit_user. php


    <?php
    include('db.php');
    session_start();
    if(!isset($_SESSION['email']))
    {
        // not logged in
        header('Location: login.php');
        exit();
    }
    
        if(isset($_POST['editId']))
        {
            $id=$_POST['editId'];
            $query="SELECT id,name,email,position from `users` where id = '$id' ";
            $result=mysqli_query($conn,$query);
            $row=mysqli_fetch_assoc($result);
            echo json_encode($row);
        }
    
        if(isset($_POST['update']))
        {
            $name = $_POST['name'];
            $email = $_POST['email'];
            $position = $_POST['position']; 
            $id = $_POST['id'];
            
            
            $query1 = "UPDATE `users` SET name='$name',email='$email', position='$position' WHERE id='".$id."'";
            $result1 = mysqli_query($conn,$query1);
            $query="SELECT id,name,email,position from `users` where id = '$id' ";
            $result=mysqli_query($conn,$query);
            $row=mysqli_fetch_assoc($result);
            echo json_encode(['status'=> 'success','data'=>$row]);           
        }
        ?>

Ответы [ 2 ]

1 голос
/ 09 июля 2020

Вам необходимо предотвратить событие отправки на вашей кнопке в ваших слушателях событий onClick:

.on('click',function(e) {
  e.preventDefault(); // this prevents the submit
  ... rest of your code
}
0 голосов
/ 09 июля 2020

Преобразуйте кнопку отправки в обычную кнопку или следуйте приведенному выше ответу на preventDefault, чтобы он не делал публикацию на всю страницу и не обновлял страницу - Обсуждение ниже относится к моему недоразумению и плохим навыкам чтения блоков кода;)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...