0

I have ASP.NET Code that use JS for datatable for views. And i do some repetiting code because i have 3 tables (in this case) that i have same columns. just the data(json) that different i have got from controller.

Here's the JS Code

<script type="text/javascript">

    function parseDate(date) {
        if (!date) {
            return ""
        }
        return new Date(parseInt(date.substr(6))).toLocaleString();
    }

    $(document).ready(function() {
        $.ajax({
            "url": "@Url.Action("GetAllByUserToday", "Dashboard")",
            "type": "GET",
            "datatype": "json",
            "success": function(res) {
                const mapped = res.data.map((dt) => {
                    return {
                        ...dt,
                        CreatedDate: parseDate(dt.CreatedDate),
                        Status: dt.Status ? "Sukses" : "Gagal",
                        IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
                    };
                });

                $("#getAllToday").DataTable({
                    "data": mapped,
                    "dom": 'Bfrtip',
                    "buttons": ['copy', 'excel'],
                    "columns": [
                        { "data": "Nama" },
                        { "data": "NoHP" },
                        { "data": "Content" },
                        { "data": "Sender" },
                        { "data": "IsUsingTemplate" },
                        { "data": "Status" },
                        { "data": "CreatedDate" }
                    ],
                    columnDefs: [{ 'targets': 0, type: 'date-euro' }],
                    order: [0, 'desc'],
                });
            }
        });

        $("#getAll_wrapper").addClass("w-100");

    });

    $(document).ready(function() {
        $.ajax({
            "url": "@Url.Action("GetAllSentByUserToday", "Dashboard")",
            "type": "GET",
            "datatype": "json",
            "success": function(res) {
                const mapped = res.data?.map((dt) => {
                    return {
                        ...dt,
                        CreatedDate: parseDate(dt.CreatedDate),
                        Status: dt.Status ? "Sukses" : "Gagal",
                        IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
                    };
                });


                $("#getAllSentToday").DataTable({
                    "data": mapped,
                    "dom": 'Bfrtip',
                    "buttons": ['copy', 'excel'],
                    "columns": [
                        { "data": "Nama" },
                        { "data": "NoHP" },
                        { "data": "Content" },
                        { "data": "Sender" },
                        { "data": "IsUsingTemplate" },
                        { "data": "Status" },
                        { "data": "CreatedDate" }
                    ],
                    columnDefs: [{ 'targets': 0, type: 'date-euro' }],
                    order: [0, 'desc'],
                });
            }
        });
    });

    $(document).ready(function() {
        $.ajax({
            "url": "@Url.Action("GetAllFailedByUserToday", "Dashboard")",
            "type": "GET",
            "datatype": "json",
            "success": function(res) {
                const mapped = res.data.map((dt) => {
                    return {
                        ...dt,
                        CreatedDate: parseDate(dt.CreatedDate),
                        Status: dt.Status ? "Sukses" : "Gagal",
                        IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
                    };
                });

                $("#getAllFailedToday").DataTable({
                    "data": mapped,
                    "dom": 'Bfrtip',
                    "buttons": ['copy', 'excel'],
                    "columns": [
                        { "data": "Nama" },
                        { "data": "NoHP" },
                        { "data": "Content" },
                        { "data": "Sender" },
                        { "data": "IsUsingTemplate" },
                        { "data": "Status" },
                        { "data": "CreatedDate" }
                    ],
                    columnDefs: [{ 'targets': 0, type: 'date-euro' }],
                    order: [0, 'desc'],
                });
            }
        });


    });

</script>

Can I reduce the repetition for these code. If can, please help me. So I can try to apply for another page that has same issue. Thank you.

9
  • Your question is very broad. From what I can see in your example you could move the duplicate configs for the DataTable(...) callback into an object and then pass the reference to the functions. You can also define the mapper function at the beginning ad then just call it with the data, so that you don't repeat it everytime Commented Dec 22, 2021 at 9:35
  • I’m voting to close this question because this question belongs on codereview.stackexchange.com Commented Dec 22, 2021 at 9:36
  • Put a lightly modified version of the ajax etc into a function that accepts ‘action‘ and ‘tableID‘ parameters ,(I think they are the only ones). Then call the function three times, each with its own action/tableID. Do all this inside a single ‘jQuery(document).ready()‘ wrapper. Commented Dec 22, 2021 at 11:02
  • Im Sorry @VincentMenzel I'm new in JS. can you give me the example? Commented Dec 23, 2021 at 6:24
  • @Roamer-1888 NICE, i have tried this and i just call the URL and tableId. ot works. Thanks :) Commented Dec 23, 2021 at 6:52

1 Answer 1

1

Update, suggestion from @Roamer-1888 finally I try this and it works!

function renderTable(action, tableId) {
    $.ajax({
        "url": action,
        "type": "GET",
        "datatype": "json",
        "success": function(res) {
            const mapped = res.data.map((dt) => {
                return {
                    ...dt,
                    CreatedDate: parseDate(dt.CreatedDate),
                    Status: dt.Status ? "Sukses" : "Gagal",
                    IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
                };
            });

            $(tableId).DataTable({
                "responsive": true,
                "lengthChange": false,
                "autoWidth": false,
                "data": mapped,
                "dom": 'Bfrtip',
                "buttons": ['copy', 'excel'],
                "columns": [
                    { "data": "Nama" },
                    { "data": "NoHP" },
                    { "data": "Content" },
                    { "data": "Sender" },
                    { "data": "IsUsingTemplate" },
                    { "data": "Status" },
                    { "data": "CreatedDate" }
                ],
                columnDefs: [{ 'targets': 0, type: 'date-euro' }],
                order: [0, 'desc'],
            });

        }
    });
}

$(document).ready(function() {
    renderTable("@Url.Action("GetAllByUser", "Dashboard")", "#getByUser")
    renderTable("@Url.Action("GetAllSentByUser", "Dashboard")", "#getSentByUser")
    renderTable("@Url.Action("GetAllFailedByUser", "Dashboard")","getFailedByUser")
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.