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
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
When you say
page reload
do you mean that the table displays page 1 after thedraw()
? If so you can usedraw(false)
to stay on the same page. the docs explain this parameter.Kevin
Nope, tried that and still not working.
I have an
input field
and and abutton
in aform
tag, what i am trying to do this in the above code is that when i click on thatbutton
it sends anajax
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 thedatatable
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
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?
In your Datatables init code you are using
columns.render
to build the buttons. So you shouldn't need them above. Plusrow.add()
only adds one row so it is not expecting an array. My guess is you need this: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
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");
}
});
});
@kthorngren
The response i get from the
url: 'http://localhost:3000/api/post/getUserData'
in my code is in this formatIn this function i first
post
theinput
to server which then is saved in theDB
and in it's success function i try to make anotherAJAX
call to fetch that newly inserted data and in thesuccess
function of this secondAJAX
call i try to display it in theDataTables
and this is where things go wrong.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 putrow.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.
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
Yes i saw,
getUserData
endpoint is not being called inside the second `success' function.This ajax request is not working.
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 thehttp://localhost:3000/userShrink
request causing thesuccess
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