简体   繁体   English

以模式更新数据表(ajax javascript)

[英]Update datatable in a modal (ajax javascript)

利斯塔多

I have a modal that contains a datatable that is called from another main datatable, to raise the modal I execute the following function with their respective validations我有一个包含从另一个主数据表调用的数据表的模态,为了提高模态我执行以下 function 及其各自的验证

   var getDataDiseases = function (tbody, table)
    {
        $(tbody).on("click", "button.disease-button", function ()
        {
            var data = table.row($(this).parents("tr")).data();
           
            var id = data.id;
            var fullName = data.fullName;

            if (id != null)
            {
                GetDiseases(id, fullName);
            }
            else
            {
                toastr.error('Ha ocurrido un problema, intente más tarde', "Error");
            }
        });
    }    

    getDataDiseases("#TableUsers tbody", table); 


 function GetDiseases(id, fullName)
    {  
        $.ajax({
            type: "POST",
            url: "/DiseaseTypes/GetDiseasesByUser",
            data: { id: id },
            success: function (response)
            {
                ReloadDataTableModal(response);       

                var nombreUser = document.getElementById('title-strong-diseases');
                nombreUser.innerHTML = fullName

                $("#diseases-modal").modal();
            },
            error: function (xhr, status, error)
            {
                console.log("error");
                toastr.error(error, "Error");
            }
        });     
     
    }

In the getDiseases function if the ajax call returns success, load or reload the datatable with the information answered through another function called ReloadDataTableModal which receives the information as a parameter在 getDiseases function 中,如果 ajax 调用返回成功,则使用通过另一个 function 作为参数 ReloadDataModal 接收的信息来加载或重新加载数据表以及通过另一个 function 回答的信息

   function ReloadDataTableModal(response)
    {
        //Se destrute el Dt
        $('#TableDiseasesUser').DataTable().clear();
        $('#TableDiseasesUser').DataTable().destroy();

        var tableModal = $('#TableDiseasesUser').DataTable({          
            "processing": true,
            "responsive": true,
            "destroy": true,
            data: response,
            "columns": [
                { "data": "diseaseId", "autoWidth": true },
                { "data": "diseaseName", "autoWidth": true },
                { "data": "diseasedStatus", render: getToggleSwitch },

            ],
            fixedColumns: {
                heightMatch: 'none'
            },
            "language": {
                "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
            },
            "aLengthMenu": [
                [25, 50, 100, 200, -1],
                [25, 50, 100, 200, "Todos"]
            ]
        });

        var getDataDiseasesByUser = function (tbody, tableModal)
        {
            $(tbody).on("click", "input.toggle-disease", function ()
            { 
                var data = tableModal.row($(this).parents("tr")).data();

                console.log($(this));
                console.log(data);

                ActionAddDiseaseToUser(data);
            });
        }

        getDataDiseasesByUser("#TableDiseasesUser tbody", tableModal);

    }

Within this same function, I also load the "click" listening event for when the swicht is turned on or off and thus update the datatable在同一个 function 中,我还加载了开关打开或关闭时的“点击”监听事件,从而更新数据表

The problem that is occurring is that the switch only works the first time it is executed, when it is executed for the second time the data is not found in the line marked by the arrow and therefore that variable has the value of undefined发生的问题是开关仅在第一次执行时才起作用,当第二次执行时,在箭头标记的行中找不到数据,因此该变量的值为 undefined

代码

To do this I print the value of each of the "TR" of the row that calls the modal button为此,我打印调用模式按钮的行的每个“TR”的值

价值观

What the ActionAddDiseaseToUser method does is update a column in the Database and return the new Json (by backend) to populate (update) again the datatable of the modal ActionAddDiseaseToUser 方法所做的是更新数据库中的列并返回新的 Json(通过后端)以再次填充(更新)模态的数据表

  function ActionAddDiseaseToUser(data)
    {
        var userDiseaseObject = {};

        userDiseaseObject.userId = data.userId;
        userDiseaseObject.firstName = data.firstName;
        userDiseaseObject.lastName = data.lastName;
        userDiseaseObject.diseaseId = data.diseaseId;
        userDiseaseObject.diseaseName = data.diseaseName;
        userDiseaseObject.diseasedStatus = data.diseasedStatus;        

        $.ajax({
            type: "POST",
            url: "/Users/AddDiseaseToUser",
            data: JSON.stringify(userDiseaseObject),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response)
            {
                if (response)
                {                   
                    ReloadDataTableModal(response);

                    toastr.success('Se ha actualizado la enfermedad ' + data.diseaseName + ' al usuario ' + data.firstName + ' ' + data.lastName, "Guardado");                
                }
            },
            error: function (xhr, status, error)
            {
                toastr.error(error, "Error");
            }
        });
    }

What's going on?这是怎么回事? Why does my logic only work the first time the switch is activated or deactivated?为什么我的逻辑只在开关第一次激活或停用时才起作用? Why is it that the second time I click on the switch, I can't find the data in the corresponding row?为什么我第二次点击开关,却找不到对应行的数据? I have destroyed and cleaned the datatable but it does not solve the problem... any help for me?我已经销毁并清理了数据表,但它并没有解决问题......对我有什么帮助吗?

In your modal, have a table defined with an ID, a <thead> and an empty <tbody> .在您的模式中,有一个用 ID、一个<thead>和一个空的<tbody>定义的表。

<table id="TableDiseasesUser" style="width: 100%;">
    <thead>
        <tr>
            <th>Disease ID</th>
            <th>Disease Name</th>
            <th>Disease Status</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

In your JavaScript, define your DataTable and assign it to a variable.在您的 JavaScript 中,定义您的 DataTable 并将其分配给一个变量。 Because you are using POST, the ajax property needs to be an object:因为您使用的是 POST,所以ajax属性需要是 object:

const tableModal = $('#TableDiseasesUser').DataTable({          
    "processing": true,
    "responsive": true,
    "ajax": {
        method: "POST",
        url: "/DiseaseTypes/GetDiseasesByUser",
        data: { id: '' }
    }
    "columns": [
        { "data": "diseaseId", "autoWidth": true },
        { "data": "diseaseName", "autoWidth": true },
        { "data": "diseasedStatus", render: getToggleSwitch },
    ],
    fixedColumns: {
        heightMatch: 'none'
    },
    "language": {
        "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
    },
    "aLengthMenu": [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "Todos"]
    ]
});

In your server side code, return your data as JSON.在您的服务器端代码中,将您的数据返回为 JSON。 You haven't shown me any so I don't know which language you use, but I use PHP你没有给我看所以我不知道你使用哪种语言,但我使用 PHP

$data = getMyData(); // returns an array
echo json_encode(["data" => $data]); // echo an object with property "data" that has value the $data array

Then when you want to (re-)populate your table you set the ajax.data property and call its reload() function然后,当您想(重新)填充您的表时,您设置ajax.data属性并调用它的reload() function

function ReloadDataTableModal(newID) {
    tableModal.ajax.data = { id: newID };
    tableModal.ajax.reload();
}

For your click event, refer to the table variable you defined earlier对于您的点击事件,请参考您之前定义的表变量

tableModal.on('click', 'input.toggle-disease', function() {
    const data = tableModal.row($(this).closest('tr')).data();
}

And that's it.就是这样。 No need to call destroy() or any of that.无需调用destroy()或任何其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM