【问题标题】:Stop page refreshing after updating row through jquery ajax通过jquery ajax更新行后停止页面刷新
【发布时间】:2020-07-09 13:59:31
【问题描述】:

我的数据已成功更新,更新后它会显示在浏览器的表格中,并显示更新的行。但问题是更新后它会重新加载页面。请建议我该怎么做才能停止刷新我的页面?因为我使用 ajax jquery 来更新我的行。

我在ajax成功方法中使用了页面重新加载功能来重新加载页面,但是没有重新加载页面我的数据没有更新。

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]);           
        }
        ?>

【问题讨论】:

  • .update 回调中还有一个偷偷摸摸的location.reload(true);... 这无济于事。
  • “但问题是更新后它重新加载页面”......是的,这是真的。你认为location.reload(true) 这条线是干什么用的?线索就在名字里……

标签: javascript php html jquery ajax


【解决方案1】:

您需要在 onClick 事件侦听器中阻止按钮上的提交事件:

.on('click',function(e) {
  e.preventDefault(); // this prevents the submit
  ... rest of your code
}

【讨论】:

  • “更新”按钮在表单之外,因此不适用
  • 那个鬼鬼祟祟的过早结束形式标签 ;) 虽然在问题中称为代码的那堆乱七八糟的代码中很难发现。
【解决方案2】:

将提交按钮转换为常规按钮或按照上面对preventDefault的回答,所以它不会做整页帖子并刷新页面 - 下面的讨论,指的是我的误解和糟糕的代码块阅读能力;)

【讨论】:

  • 修改了答案以保持一致,CSS 和 HTML 之间的选择器不匹配。注意类名是 class="btn btn-info update" 和 id="insert" (来自帖子的原始代码)
  • 您误解了使用 ID 或 CLASS 作为选择器的区别。当他已经使用 .class 选择器正确处理它时,他不需要使用 #id。仅仅因为一个元素有一个 id,并不意味着所有的选择器都必须使用这个 id。您还期望如何将处理程序附加到类的多个项目上?
  • 同意评论,已修改 - 有时你不得不吃不起眼的馅饼 - 这让我失望 - ` ` 使用 Class 选择器或 ID 并不重要,我假设它们混合了 id 和 class 。重新访问了原始的询问和选择器工作正常,无论是 preventDefault 还是将提交变成一个简单的按钮。
  • 是的,这个问题的代码看起来有点乱,它也让我陷入了循环;-)
猜你喜欢
  • 1970-01-01
  • 2020-03-05
  • 2013-08-10
  • 1970-01-01
  • 2015-03-01
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
相关资源
最近更新 更多