why is this my data table not reloading?. In my situation, I have a data table named table_clinics that I declared global in my javascript, now I have other function to add a data within the data table, I want to prevent refresh that is why I want my data table to be reloaded after adding new data. Am I doing it wrong?.
Here is my code:
<script type="text/javascript">
var table_clinics;
$(document).ready(function() {
table_clinics = $('#dataTables-clinics').dataTable();
});
function show_clinics() {
$("#dataTables-clinics").dataTable().fnDestroy();
table_clinics = $('#dataTables-clinics').DataTable({
"ajax": {
"url": "<?php echo site_url('clinic_admin/myclinics')?>",
"type": "POST",
},
responsive: true,
bInfo: false,
});
}
</script>
now I have a function to add data from the data table and after success, i want to refresh my data table. Here is my function: i tried : table_clinics.ajax.reload(null,false); but it doesn't reload my data table. how can I do this?
function create_clinic() {
$('#btnCreateClinic').text('Saving...');
$('#btnCreateClinic').attr('disabled',true);
$.ajax({
url : siteurl+"clinic_admin/create_clinic",
type: "POST",
data: $('#frm_create_clinic').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) {
table_clinics.ajax.reload(null,false);
alert('Added Sucessfuly');
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
$('#btnCreateClinic').text('Save'); //change button text
$('#btnCreateClinic').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding data' + jqXHR+ textStatus +errorThrown);
$('#btnCreateClinic').text('Save');
$('#btnCreateClinic').attr('disabled',false);
}
});
}
also tried this:
if(data.status) {
table_clinics = $("#dataTables-clinics").dataTable( { bRetrieve : true } );
table_clinics.fnDraw();
// Hide all tables
$('dataTables-clinics').hide();
// Show the refreshed
$('dataTables-clinics').show();
alert('Added Sucessfuly');
}
also i tried this one:
and i add https://cdn.datatables.net/plug-ins/1.10.15/api/fnReloadAjax.js.
if(data.status) {
table_clinics.fnReloadAjax('<?php echo site_url('"clinic_admin/myclinics"')?>');
table_clinics.fnReloadAjax();
alert('Added Sucessfuly');
}
Reload You datatable , Try this
$('#dynamic-table').DataTable().ajax.reload(); // id of table
You must call draw() on the datatable object.
var oTable = $('#yourDataTable').dataTable();
oTable.fnDraw();
See the example i have done. Click on Add New Data button in jsfiddle
Related
I am using a DataTable and an onclick event that checks if im clicking a certain td, then im validating the selection with a yes no. If i place DataTable.row().remove() here it works fine. But if i move the same item on the ajax success function it does not work - im sure im not understanding how java functions work, see code below - please help :)
<script>
var table = $('#notesTable').DataTable({
searching: false,
"pageLength": 15
});
$('#notesTable tbody').on('click', 'td', function (table) {
var noteIDObject = this.parentNode.cells[0];
var noteID = noteIDObject.id;
var currentRow = event.currentTarget.parentNode.rowIndex;
if (this.id == "trashRow") {
let confirmAction = confirm("Are you sure you want to delete this record?");
if (confirmAction) {
var p = $('#notesTable').DataTable();
p.row($(this).parents('tr')).remove().draw();
$.ajax({
type: "POST",
url: "/ClientDetails/DeleteNote/",
data: { noteID },
success: function (response) {
if (response == 200) {
console.log(200);
//would like to remove the row here on a successfull response
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
} else {
}
} else { }
});
I have a simple messaging system and I am retrieving the messages from the DB using jQuery/AJAX and appending to a table. I wanted pagination for the messages so I opted to use the DataTables plugin (https://datatables.net/).
I am having trouble using this with my dynamically generated data. I also have functions such as "delete message" which would then delete the message and then retrieve the messages again (refresh the table). I am getting the error "cannot re-initialise DataTable".
This is my code so far:
function getmessages(){
$.ajax({
type: "POST",
url: "modules/ajaxgetmessages.php",
dataType: 'json',
cache: false,
})
.success(function(response) {
if(!response.errors && response.result) {
$("#tbodymessagelist").html('');
$.each(response.result, function( index, value) {
var messagesubject = value[3];
var messagecontent = value[4];
var messagetime = value[5];
var sendername = value[2];
var readstatus = value[7];
var messageid = value[8];
if (readstatus==0){
messageheader += '<tr><td><input type="checkbox" class="inboxcheckbox input-chk"></td><td class="sendername"><b>'+sendername+'</b></td><td class="messagesubject"><b>'+messagesubject+'</b></td><td><b>'+messagetime+'</b></td><td class="messageid" style="display:none">'+messageid+'</td><td class="readstatus" style="display:none">'+readstatus+'</td><td class="messagecontent" style="display:none"><b>'+messagecontent+'</b></td></tr>';
} else {
messageheader += '<tr><td><input type="checkbox" class="inboxcheckbox input-chk"></td><td class="sendername">'+sendername+'</td><td class="messagesubject">'+messagesubject+'</td><td>'+messagetime+'</td><td class="messageid" style="display:none">'+messageid+'</td><td class="readstatus" style="display:none">'+readstatus+'</td><td class="messagecontent" style="display:none"><b>'+messagecontent+'</b></td></tr>';
}
});
$("#tbodymessagelist").html(messageheader);
$('#tblinbox').DataTable({
"paging": true,
"ordering": false,
"info": false
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
So how can I essentially, make changes to my table after message deletion or other functions and then "refresh" the table? It also shows Showing 0 to 0 of 0 entries in the footer even though there are entries there.
You must destroy datatable berfore create new instance;
`
$('#tblinbox').DataTable.destroy();
$('#tblinbox').empty();
I am insert the data in mysql database using ajax on submitting this error will appaer .I am making this
in codeigniter framework. I am new bie to ajax.I am not able to figure out where am going wrong .Here is my code
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;
// if (save_method == 'add') {
url = "http://[::1]/sms/sms/forms/1";
// } else {
// url = "";
//// }
var radio=$('#radio').val();
var st_id=$('#st_id').val();
var branch_type=$('#branch_type').val();
bname=$('#bname').val();
bcode=$('#bcode').val();
baddress=$('#baddress').val();
var bcity=$('#bcity').val();
var zcode=$('#zcode').val();
var bstates=$('#bstates').val();
var bcountry=$('#bcountry').val();
var bpno=$('#bpno').val();
var bemail=$('#bemail').val();
var bweb=$('#bweb').val();
var Latitude=$('#Latitude').val();
var Longtitude=$('#Longtitude').val();
var noted=$('#noted').val();
var addedby=$('#addedby').val();
// ajax adding data to database
$.ajax({
type: 'ajax',
data: {st_id: st_id, branch_type: branch_type, bname: bname, bcode: bcode, baddress: baddress,
bcity: bcity, zcode: zcode, bstates: bstates, bcountry: bcountry, bpno: bpno, bemail: bemail,
bweb: bweb, Latitude: Latitude, Longtitude: Longtitude, noted: noted, addedby: addedby},
url: url,
method: 'post',
asysc: false,
dataType: 'json',
success: function (data) {
if (data.status) //if success close modal and reload ajax table
{
}
else {
}
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + textStatus + errorThrown);
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
//
}
});
my php code
$submit['sys_t_id']=$this->input->post('st_id');
$submit['t_id']=$this->input->post('branch_type');
$submit['name']=$this->input->post('bname');
$submit['code']=$this->input->post('bcode');
$submit['address']=$this->input->post('baddress');
$submit['city']=$this->input->post('bcity');
$submit['zip']=$this->input->post('zcode');
$submit['state']=$this->input->post('bstates');
$submit['country']=$this->input->post('bcountry');
$submit['contact_no']=$this->input->post('bpno');
$submit['email']=$this->input->post('bemail');
$submit['web']=$this->input->post('bweb');
$submit['latitude']=$this->input->post('Latitude');
$submit['longitude']=$this->input->post('Longtitude');
$submit['note']=$this->input->post('noted');
$submit['addedby']=$this->input->post('addedby');
$submit['addedon']=date('Y-m-d:H-m-s');
$insert = $this->Smsmodal->insert('branch_info',$submit);
echo json_encode(array("status" => TRUE));
I think you have server error! Use console.log(data) in you success function for see server output.
I want to ask why my codeigniter when add data become error 500 internal server when the save proccess. I dont know anything about this problem please help me all.
This is ajax code in view
function save()
{
$('#btnSave').text('menyimpan...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('edulibs/ajax_add')?>";
} else {
url = "<?php echo site_url('edulibs/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('menambahkan / update data error');
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
And this is my controller
public function ajax_add()
{
$this->_validate();
$data = array(
'nama' => $this->input->post('nama'),
'nim' => $this->input->post('nim'),
'pembimbing1' => $this->input->post('pembimbing1'),
'pembimbing2' => $this->input->post('pembimbing2'),
'subyek' => $this->input->post('subyek'),
'judul' => $this->input->post('judul'),
'tanggal' => $this->input->post('tanggal'),
'tautan' => $this->input->post('tautan'),
);
$insert = $this->edulibs->save($data);
echo json_encode(array("status" => TRUE));
}
In order to use site_url() load url helper in your controller first.like this..
$this->load->helper('url');
OR load helper in application/config/autoload.php
And in success function of your ajax use JSON.parse() to parse your json response into object.Like this
success: function(response)
{
var data = JSON.parse(response);//OR var data = eval(response);
if(data.status) //if success close modal and reload ajax table
{
//code here
}
else
{
//code here
}
For my course purpose I want to create a dynamic data table using ajax. Here's my Javascript code:
$("#submitcateg").click(function(){
var categ = $("#addcategname").val();
$.ajax({
type: "POST",
url: "ProcatServlet",
data: {"categ":categ, "id":"addcateg"},
success: function(data){
if(data=="true"){
$("#addcategname").hide();
$("#submitcateg").hide();
$("#categtable").show(function(){
$.ajax({
type: "GET",
url: "ProcatServlet",
data: {"id":"getcateg"},
success: function(responseJson) {
if(responseJson!=null) {
$("#categtable").find("tr:gt(0)").remove();
var tablebody = document.getElementById("categtable").getElementsByTagName("tbody");
$.each(responseJson, function(key, value){
var button = document.createElement("input");
button.type="button";
button.id="edit";
button.value="edit";
var rowNew = $("<tr><td></td><td></td></tr>");
rowNew.children().eq(0).text(value);
rowNew.children().eq(1).append(button);
rowNew.appendTo(tablebody);
});
}
}
});
});
$("#addcategtrigger").show();
} else {
alert("failed");
}
}
});
});
Using this code, I can show the data and assigned it to the table perfectly, but when I'm trying to add a button to the next column on the row, the button didn't appear. Please help me where I'm doing it wrong.