如何在不刷新的情况下执行 jquery ajax 来重新加载我的数据

Posted

技术标签:

【中文标题】如何在不刷新的情况下执行 jquery ajax 来重新加载我的数据【英文标题】:How can I perform jquery ajax to reload my data without refreshing 【发布时间】:2021-02-09 09:12:27 【问题描述】:

我的问题是当我插入或更新一个值时,此代码不起作用,但我网络中的状态代码显示 200 表示正常

我想获取 tbody 部分中的任何数据,我在其中获取所有数据

这是我的全部代码

这是我的 html 代码,页面重新加载后我的表格会放在这里

        <!-- Table starts -->
        <div class="container-fluid">
            <table class="table table-hover table-responsive">
                <thead class="table-head">
                    <tr>
                        <th>Action</th>
                        <th>ID</th>
                        <th>Username</th>
                        <th>Password</th>
                        <th>Birthday</th>
                        <th>Age</th>
                        <th>Mobile #</th>
                        <th>Address</th>
                        <th>Gender</th>
                        <th>Nickname</th>
                        <th>Occupation</th>
                    </tr>
                </thead>

                <tbody class="tbody">
                </tbody>
            </table>
        </div>
        <!-- Table ends -->

这是我在脚本中的代码,我正在使用 jquery ajax 来执行它。

    //view existing data
    function viewData()
        $.ajax(
            method: 'POST',
            url: 'server.php',
            dataType: 'text',
            data: 
                key: 'viewData',
            ,
            success: function(response)

                //this is my problem
                $('.tbody').append(response);

                //After I changed the append to html it works OMG!
                //just like this
                $('.tbody').html(response);

                $(".table").DataTable();
            
        );
    


//Insert data
    function manageData(key)
        var username = $('#username');
        var password = $('#password');
        var birthday = $('#birthday');
        var age = $('#age');
        var mobileNumber = $('#mobile-number');
        var fullAddress = $('#full-address');
        var gender = $('#gender');
        var nickname = $('#nickname');
        var occupation = $('#occupation');
        var editRowID = $('#editRowID');
        var query = window.location.search;

        if(isNotEmpty(username) && isNotEmpty(password) && isNotEmpty(birthday)
        && isNotEmpty(age) && isNotEmpty(mobileNumber) && isNotEmpty(fullAddress) 
        && isNotEmpty(gender) && isNotEmpty(nickname) && isNotEmpty(occupation))
            $.ajax(
                method: 'POST',
                url: query + '/Dental-Clinic/admin/server.php',
                dataType: 'text',
                data: 
                    key: key,
                    username: username.val(),
                    password: password.val(),
                    birthday: birthday.val(),
                    age: age.val(),
                    mobileNumber: mobileNumber.val(),
                    fullAddress: fullAddress.val(),
                    gender: gender.val(),
                    nickname: nickname.val(),
                    occupation: occupation.val(),
                    rowID: editRowID.val()
                ,
                success: function(response)
                    username.val(""),
                    password.val(""),
                    birthday.val(""),
                    age.val(""),
                    mobileNumber.val(""),
                    fullAddress.val(""),
                    gender.val(""),
                    nickname.val(""),
                    occupation.val(""),        
                    $(".modal").modal('hide');
                    viewData();
                
            );
        
    

这是我的 server.php

 //view/refresh data when new record has been saved

if(isset($_POST['key']))
    if($_POST['key'] == 'viewData')

        $query = "SELECT * FROM patient_table";
        $result = $connection->query($query);

        if ($result->num_rows > 0)
            $response = '';
            // output data of each row
            while($row = $result->fetch_array()) 
                $response .='
                    <tr>
                        <td class="d-flex justify-content-between"> <!--To align the button-->
                            <button class="btn btn-primary" onclick="edit('.$row["id"].')" id="edit" value="Edit"><i class="fas fa-edit"></i></button>
                            <button class="btn btn-danger" id="delete"><i class="fas fa-trash-alt"></i></button>
                        </td>
                        <td>'.$row["id"].'</td>
                        <td>'.$row["username"].'</td>
                        <td>'.$row["password"].'</td>
                        <td>'.$row["birthday"].'</td>
                        <td>'.$row["age"].'</td>
                        <td>'.$row["mobile_number"].'</td>
                        <td>'.$row["full_address"].'</td>
                        <td>'.$row["gender"].'</td>
                        <td>'.$row["nickname"].'</td>
                        <td>'.$row["occupation"].'</td>
                    </tr>
                ';
            
            echo($response);

         else
            exit('no data');
    



    //Insert data
    $username = $connection->real_escape_string($_POST['username']);
    $password = $connection->real_escape_string($_POST['password']);
    $birthday = $connection->real_escape_string($_POST['birthday']);
    $age = $connection->real_escape_string($_POST['age']);
    $mobileNumber = $connection->real_escape_string($_POST['mobileNumber']);
    $fullAddress = $connection->real_escape_string($_POST['fullAddress']);
    $gender = $connection->real_escape_string($_POST['gender']);
    $nickname = $connection->real_escape_string($_POST['nickname']);
    $occupation = $connection->real_escape_string($_POST['occupation']);
    $rowID = $connection->real_escape_string($_POST['rowID']);

    //add new data when manageData('addNew'); btn is clicked
    if($_POST['key'] == 'addNew')
        $query = "INSERT INTO patient_table (username, password, birthday, age, mobile_number, full_address, gender, nickname, occupation) VALUES ('$username', '$password', '$birthday', '$age', '$mobileNumber', '$fullAddress', '$gender', '$nickname', '$occupation')";
        $result = $connection->query($query);
        if ($result) 
            echo '<script>alert("Successfully Inserted");</script>';
         else 
            echo "Error: " . $query . "<br>" . $connection->error;
            exit("Error connecting to the database");
        
    

【问题讨论】:

在 ajax 调用后您是否无法看到表中的任何数据,或者您看到重复的数据?只是想知道确切的问题是什么? 我在重新加载页面时能够看到插入或更新的数据,并且我不想在插入或更新任何数据时刷新页面 @Jannus Domingo 请向我们展示您的插入 ajax jquery 代码。 @KUMAR 看到上面更新的代码,jquery中的insert和server.php中的insert @JannusDomingo 请在success:function 之后调用viewData(); 函数。 【参考方案1】:

我在这里假设像这样你有一个插入代码:-

HTML 代码:-

<form id="FORM_ID" method="post">
    <input type="text" name="name" id="name"/>
    <input type="submit" name="submit" value="Insert" />
</form>

jQuery Ajax 代码:-

<script>
  $("#FORM_ID").submit(function() 
                var name= $("#name").val();
               
                $.ajax(
                    type: "POST",
                    url: "insert.php",
                    data: "name=" + name,
                    success: function(data) 
                       function viewData();   // here call your viewData()
                          name.val("");  
                    
                );
            );
</script>

【讨论】:

【参考方案2】:

HTML

<!-- Table starts -->
<div class="container-fluid">
    <table class="table table-hover table-responsive" id="allData">
        <thead class="table-head">
            <tr>
                <th>Action</th>
                <th>ID</th>
                <th>Username</th>
                <th>Password</th>
                <th>Birthday</th>
                <th>Age</th>
                <th>Mobile #</th>
                <th>Address</th>
                <th>Gender</th>
                <th>Nickname</th>
                <th>Occupation</th>
            </tr>
        </thead>
        <tbody class="tbody" id="viewdata">
        </tbody>
    </table>
</div>
<!-- Table ends -->

JS

function viewData()
       var html = "<tr>";
        $.ajax(
            method: 'POST',
            url: 'server.php?apicall=fetch_all',
            type: 'POST',
            cache: false,
            success: function(response)
                var parsedResponse = JSON.parse(response);
                if(parsedResponse['error']=== false)
                     $.each(parsedResponse['details'],function(index,item)
                        html += "<td>"+item.id+"</td>";
                        html += "<td>"+item.username+"</td>";
                        html += "<td>"+item.password+"</td>";
                        html += "<td>"+item.email+"</td>";
                        html += "<td>"+item.birthday+"</td>";

                        html += '<td><a href="#" class="btn btn-primary edit" id=' + item.id+ '><i class="fa fa-edit"></i></a>&nbsp;&nbsp;<a href="#" class="btn btn-danger delete_item" id=' + item.id+ '><i class="fa fa-trash"></i></a></td>';
                        html += "</tr>";
                        $("#viewdata").html(html);
                    );
                
                                    
            ).done(function (data) 
        $('#allData').DataTable();
    );;


 $(document).ready(function()
   viewData(); 
   $('form').submit(function(e)
        e.preventDefault();
        var formdata = new FormData(this);
        $.ajax(
        method: 'POST',
            url: 'server.php?apicall=add_new',
            type: 'POST',
            data: formData,
            processData: false,
            cache: false,
            success: function(response)
                var parseresponse = JSON.parse(response);
                if(response["error"] === false && response["message"] === "success")
                    alert("success");
                else
                    alert("Error");
                
            
        ).done(function (data) 
            $('#allData').DataTable();
        );
    );
);

server.php

$response = array();

if (isset($_GET['apicall'])) 
    switch ($_GET['apicall']) 
        case 'fetch_all':
                $details = array();
                $sql= mysqli_query(conn, query); 
                if($sql)
                    while($rec= mysqli_fetch_array($sql) )
                        array_push($details, $rec);
                    
                    $response['error'] = false;
                    $response['message'] = 'has data';
                    $response['details'] = $details;
                else
                    $response['error'] = true;
                    $response['message'] = 'Error Occured';
                
            break;
        case 'add_new':
                $username = $connection->real_escape_string($_POST['username']);
                $password = $connection->real_escape_string($_POST['password']);
                $birthday = $connection->real_escape_string($_POST['birthday']);
                $age = $connection->real_escape_string($_POST['age']);
                $mobileNumber = $connection->real_escape_string($_POST['mobileNumber']);
                $fullAddress = $connection->real_escape_string($_POST['fullAddress']);
                $gender = $connection->real_escape_string($_POST['gender']);
                $nickname = $connection->real_escape_string($_POST['nickname']);
                $occupation = $connection->real_escape_string($_POST['occupation']);
                $sql= mysqli_query(conn, query); 
                if($sql)
                    $response['error'] = false;
                    $response['message'] = 'success';
                else
                    $response['error'] = true;
                    $response['message'] = 'Error Occured';
                
            break;
        default:
            $response['error'] = true; 
            $response['message'] = 'Invalid Operation Called';
            break;
    
else
    $response['error'] = true; 
    $response['message'] = 'Invalid API Call';

echo json_encode($response);

【讨论】:

很高兴知道。顺便说一句,您也可以选择此方法。有点冗长但容易 哦,我稍后会试试@AsadMehmood :) @JannusDomingo 慢慢来

以上是关于如何在不刷新的情况下执行 jquery ajax 来重新加载我的数据的主要内容,如果未能解决你的问题,请参考以下文章

如何在不刷新网页的情况下使用 ajax 和 jquery 动态更改 Datatables 的多个列标题?

如何在不刷新页面加载的情况下保留 jQuery 和 Bootstrap 功能?

使用 jQuery-AJAX 向 PHP 提交表单并在不刷新的情况下在 div 中显示新内容的问题

如何在不刷新的情况下使用 Ajax 在 ASP.NET MVC 中保存表单数据

无需刷新页面如何使用 ajax/jQuery 显示数据库中的值

如何在不刷新页面的情况下使用 ajax 保存 acf_form