以模式更新数据表(ajax javascript) [英] Update datatable in a modal (ajax javascript)

查看:17
本文介绍了以模式更新数据表(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

   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");
            }
        });     
     
    }

在 getDiseases 函数中,如果 ajax 调用返回成功,则通过另一个名为 ReloadDataTableModal 的函数将响应的信息加载或重新加载数据表,该函数将信息作为参数接收

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

   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);

    }

在同一个函数中,我还加载了click"开关打开或关闭时的监听事件,从而更新数据表

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

出现的问题是switch只在第一次执行的时候起作用,第二次执行的时候在箭头标记的那一行没有找到数据,所以那个变量的值是undefined

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

为此,我打印了每个TR"的值.调用模态按钮的行

To do this I print the value of each of the "TR" of the row that calls the modal button

ActionAddDiseaseToUser 方法所做的是更新数据库中的一列并返回新的 Json(通过后端)以再次填充(更新)模态的数据表

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

  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?

当前行为:

推荐答案

在您的模态中,定义一个表,其中包含一个 ID、一个 和一个空的 ;.

In your modal, have a table defined with an ID, a <thead> and an empty <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>

在您的 JavaScript 中,定义您的 DataTable 并将其分配给一个变量.因为您使用的是 POST,所以 ajax 属性需要是一个对象:

In your JavaScript, define your DataTable and assign it to a variable. Because you are using POST, the ajax property needs to be an 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"]
    ]
});

在您的服务器端代码中,将您的数据作为 JSON 返回.你没有给我看,所以我不知道你用的是哪种语言,但我用的是 PHP

In your server side code, return your data as JSON. You haven't shown me any so I don't know which language you use, but I use PHP

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

然后当你想(重新)填充你的表时,你设置 ajax.data 属性并调用它的 reload() 函数

Then when you want to (re-)populate your table you set the ajax.data property and call its 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();
}

就是这样.无需调用 destroy() 或任何其他方法.

And that's it. No need to call destroy() or any of that.

这篇关于以模式更新数据表(ajax javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆