How to add a new Row in Datatables after successful form submission using AJAX

How to add a new Row in Datatables after successful form submission using AJAX

zulfiqarqureshi619zulfiqarqureshi619 Posts: 4Questions: 1Answers: 0

Hello there,
Can anyone tell me how to add a new row in a current datatable without page refresh after a successful AJAX call. This is my code

$(document).ready(()=>{
$.ajax({
    url: 'http://localhost:3000/api/post/getUserData',
    method: 'post',
    dataType: 'json',
    data: {
        "email": window.email,
        "token": window.token
    },
    success: function(data){
        let table = $('#datatable').dataTable({
        data: data,
        "autoWidth": true,
        columns: [
                {'data': 'id'},
                {'data': 'main'},
                {'data': 'shrinked'},
                {'data': 'clicks'},
                {"data": "id",
                    "render": function ( data, type, row, meta ) {
                        return `<button data-id=${data} onclick="disableThis(event)" class="btn btn-warning">Disable</button>`
                    }
                },
                {"data": "id",
                    "render": function ( data, type, row, meta ) {
                        return `<button data-id=${data} onclick="deleteThis(event)" class="btn btn-danger">Delete</button>`
                    }
                }
            ]
        })
//function to add new Row inside Datatable
        $(function () {
            $('#form').bind('submit', function (event) {
                // using this page stop being refreshing
                event.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: 'http://localhost:3000/userShrink',
                    data: {
                        fullUrl: $('#Url').val(),
                        email: window.email,
                        token: window.token
                    },
                    success: function () {
                        $.ajax({
                            url: 'http://localhost:3000/api/post/getUserData',
                            method: 'post',
                            dataType: 'json',
                            data: {
                                "email": window.email,
                                "token": window.token
                            },
                            success: function(data){
                                table
                                    .row.add([
                                        data.id,
                                        data.main,
                                        data.shrinked,
                                        data.clicks,
                                        `<button data-id=${data} onclick="disableThis(event)" class="btn btn-warning">Disable</button>`,
                                        `<button data-id=${data} onclick="deleteThis(event)" class="btn btn-danger">Delete</button>`
                                    ])
                                    .draw()
                            }
                        })
                    }
                });
            });
        });
    }
})
})





function deleteThis(e){
console.log(e.target.getAttribute('data-id'))
}

function disableThis(e){
console.log(e.target.getAttribute('data-id'))
}

I have tried many different methods, including clear() before adding new rows , but nothing seems to work. I just wanna add a new row without page reload when data is returned in the very last success call.

P.S: Data is being successfully inserted in the DB and is also shown in Datatables as a new row when page is reloaded by the user, i just wanna do this without page reload.

Help is really appreciated, i am still stuck in this one Thank you.

Answers

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    When you say page reload do you mean that the table displays page 1 after the draw()? If so you can use draw(false) to stay on the same page. the docs explain this parameter.

    Kevin

  • zulfiqarqureshi619zulfiqarqureshi619 Posts: 4Questions: 1Answers: 0

    Nope, tried that and still not working.
    I have an input field and and a button in a form tag, what i am trying to do this in the above code is that when i click on that button it sends an ajax post request to an api so that the sent data is processed an stored in the DB and immediately afterwards it is fetched and displayed in the datatable without any page reload.
    What can i do that achieve that, i have tried so many things but still haven't able to achieve that.
    Thank you

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    without any page reload

    Are you saying you need to refresh the entire web page to display the updated data? Just trying to understand as there are many forms of reload that can be used.

    Do you get errors in your browser's console?

                                        .row.add([
                                            data.id,
                                            data.main,
                                            data.shrinked,
                                            data.clicks,
                                            `<button data-id=${data} onclick="disableThis(event)" class="btn btn-warning">Disable</button>`,
                                            `<button data-id=${data} onclick="deleteThis(event)" class="btn btn-danger">Delete</button>`
                                        ])
    

    In your Datatables init code you are using columns.render to build the buttons. So you shouldn't need them above. Plus row.add() only adds one row so it is not expecting an array. My guess is you need this:

                                        .row.add(
                                            data.id,
                                            data.main,
                                            data.shrinked,
                                            data.clicks
     )
    

    If you still need help the copy and paste the response json from the network inspector so we can see the data structure returned. Also provide any console errors you get.

    Kevin

  • krutovdlkrutovdl Posts: 50Questions: 9Answers: 1

    Use the table variable from initialization in your case it is "table". Then use table.row.add(data).draw() where "data" is a successful return from the server. Below is an example how I did one for my employer:

    $(document).on('click', '#btnChange, function () {
    $(this).prop('disabled', true);
    $("#spErr").val('');
    $.ajax({
    type: "POST",
    url: '@Url.Action("Add", "Info")',
    data: {
    id: $(document).find('[id*="hdnId"]').val(),
    val: $("#txtValue").val(),
    edited: $('#edited).val()
    },
    datatype: "json",
    success: function (data) {
    if (data !== null) {
    var Dttm = new Date(parseInt(data.Dttm.substr(6)));
    var Chb = new Date(parseInt(data.Chb.substr(6)));
    $("#divNoData").addClass('hide');
    $("#mainList").removeClass('hide');
    data.Dttm = (Dttm.getMonth() + 1).toString() + '/' + (Dttm.getDate()).toString() + '/' + (Dttm.getFullYear()).toString();
    data.Chb = (Chb.getMonth() + 1).toString() + '/' + (Chb.getDate()).toString() + '/' + (Chb.getFullYear()).toString();
    tblCommentsList.row.add(data).order([[0, 'desc']]).draw();
    $("#display_module").modal('hide');
    }
    else {
    $("#spErr").val('There is an issue on the server. Please contact your administrator.');
    }
    },
    fail: function (xhr) {
    $("#spErr").html(xhr.status + ": " + xhr.statusText + "<br />Contact your administrator");
    }
    });
    });

  • zulfiqarqureshi619zulfiqarqureshi619 Posts: 4Questions: 1Answers: 0

    @kthorngren
    The response i get from the url: 'http://localhost:3000/api/post/getUserData' in my code is in this format

     [{
            "id": 1,
            "main": "URL",
            "shrinked": "_vkxgtu2b",
            "clicks": 0,
            "u_id": 43,
            "is_disabled": 0,
            "is_deleted": 0
        },
        {
            "id": 2,
            "main": "URL",
            "shrinked": "_2u0CDLe7",
            "clicks": 0,
            "u_id": 43,
            "is_disabled": 0,
            "is_deleted": 0
        }]
    

    In this function i first post the input to server which then is saved in the DB and in it's success function i try to make another AJAX call to fetch that newly inserted data and in the success function of this second AJAX call i try to display it in the DataTables and this is where things go wrong.

    $(function () {
                    $('#form').bind('submit', function (event) {
                        // using this page stop being refreshing
                        event.preventDefault();
    
                        $.ajax({
                            type: 'POST',
                            url: 'http://localhost:3000/userShrink',
                            data: {
                                fullUrl: $('#Url').val(),
                                email: window.email,
                                token: window.token
                            },
                            success: function () {
                                $.ajax({
                                    url: 'http://localhost:3000/api/post/getUserData',
                                    method: 'post',
                                    dataType: 'json',
                                    data: {
                                        "email": window.email,
                                        "token": window.token
                                    },
                                    success: function(data2){
                                        console.log(data2)
                                    }
                                })
                            }
                        });
                    });
                });
    

    As you can see, in the second success function, i am trying to log the data2 parameter but nothing's being logged, and i try to put row.add logic there as well, and that also show me nothing.

    If you can suggest me a better way of rendering the table/displaying the data, i am willing to change this code alltogether.
    Thank you very much for the help.

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    in the second success function, i am trying to log the data2 parameter but nothing's being logged

    Did you use the browser's network inspector tool to see the actual response? If its empty then you will need to debug your getUSerData script to find out why.

    Kevin

  • zulfiqarqureshi619zulfiqarqureshi619 Posts: 4Questions: 1Answers: 0

    Yes i saw, getUserData endpoint is not being called inside the second `success' function.

    success: function () {
                                $.ajax({
                                    url: 'http://localhost:3000/api/post/getUserData',
                                    method: 'post',
                                    dataType: 'json',
                                    data: {
                                        "email": window.email,
                                        "token": window.token
                                    },
                                    success: function(data2){
                                        console.log(data2)
                                    }
                                })
                            }
    

    This ajax request is not working.

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    Thats not a Datatables specific issue. You will need to debug the code to determine if the success function is being called. Maybe there is an error in the http://localhost:3000/userShrink request causing the success function to not be called. Maybe there is a console error.

    Stack Overflow is a more appropriate place to find answers to general Javascript and jQuery questions.

    Kevin

This discussion has been closed.