How to use ajax.reload or fnReloadAjax in Data Tables? - javascript

manage_course_subject.php code table
<table id="manage_course_subject" class="display table table-hover ">
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>
When I click onclick="return add_course_subject_form();"
In file script.js use this function
var table = $('#manage_course_subject').dataTable();
function add_course_subject_form(){
$.ajax({
type:"POST",
url:"process.php",
data:$("#add_course_subject_form").serialize(),
success:function(data){
//close modal
$(".close").trigger("click");
//show result
alert(data);
//reload page
// location.reload();
// manage_course_subject.api().ajax.reload();
// table.fnReloadAjax();
// table.api().ajax.reload();
// table.ajax.reload();
// table.api().ajax.reload();
}
});
return false;
}
When I use fnReloadAjax() I include
var imported = document.createElement('script');
imported.src = 'media/js/fnReloadAjax.js';
document.head.appendChild(imported);
I try but didn't work the 2nd way
Can anyone help me?

Related

How to initialize Datatable after ajax call

I'm trying to get data from Database then append it in table columns using ajax jquery calls. Once i get the data and add it to the Datatable i lose the Datatable functionality which is normal since i'm dynamically adding data and i have to reinitialize the plugin. But the problem is whenever i initialize it i get and error stating "DataTables warning: table id=leadsListTable - Cannot reinitialize DataTable". I went to the link and applied every step they stated, yet i still get an error !
Here's my The HTML
<div class="table-responsive">
<table class="table invoice-data-table dt-responsive nowrap" id="leadsListTable" style="width:100%">
<thead>
<tr>
<th></th>
<th></th>
<th><span class="align-middle">Client#</span></th>
<th>Name</th>
<th>Phone</th>
<th>Adresse</th>
<th>Source</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="leadsList">
</tbody>
</table>
</div>
Here's the Ajax function call
function showAllClients(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>leads/showAllClients',
async: false,
dataType: 'json',
success: function(data){
console.log(data)
var html ='';
for(i=0;i < data.length;i++){
html += '<tr>'+
'<td></td>'+
'<td></td>'+
'<td>'+data[i].lead_ID+'</td>'+
'<td>'+data[i].lead_Name+'</td>'+
'<td>'+data[i].lead_Phone+'</td>'+
'<td>'+data[i].lead_Adresse+'</td>'+
'<td>'+data[i].lead_Source+'</td>'+
'<td>'+data[i].lead_Status+'</td>'+
'<td>Edit</td>'+
'</tr>';
}
$('#leadsList').html(html);
$("#leadsListTable").dataTable({ //Tried this still getting the same error
"destroy": true,
});
},
error: function(){
alert('Could not get Data from Database');
}
});
}
Note that i did read other posts but either the solutions are outdated or they cause the same errors again. Please help !
I think that the problem might be that you destroy the datatable but never reinitialize it.
// Destroy the table
// Use $("#leadsListTable").DataTable().destroy() for DataTables 1.10.x
$("#leadsListTable").dataTable().fnDestroy()
// Reinitialize
$("#leadsListTable").dataTable({
// ... skipped ...
});
See if this works for you.

Paginating table after ajax request - JS

In my code below, when i paginate my data and filter using my search box.
What happens is, after my ajax request is successful, the table in default states returns all data without the pagination.
When i refresh the page, the table is then paginated again and after ajax request, the pagination is no more
Why is this happening?
HTML
<table class="table" id="table" >
<thead>
<tr>
<th></th>
<th colspan="5"></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($products as $product)
<tr>
<td width="600">{{$product->name }}</td>
</tr>
#endforeach
</tbody>
</table>
{{$products->links()}}
JS
<script>
$(document).ready(function () {
var typingTimer; //timer identifier
var doneTypingInterval = 100; //time in ms (5 seconds)
$("#myInput").on('keyup', function () {
clearTimeout(typingTimer);
// if ($('#myInput').val() | ) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
// }
});
});
//user is "finished typing," do something
function doneTyping() {
var key = $('#myInput').val();
$.ajax({
url: '/admin/dashboard/order/food/search?myInput='+key,
type: 'GET',
beforeSend: function () {
// $("#table").slideUp('fast');
},
success: function (data) {
console.log(data);
$("#table").slideDown('fast');
var table = $("#table tbody");
table.html("");
$.each(data, function(idx, elem){
table.append(
"<tr><td><input type='checkbox' onclick='return order(this)' data-food='"+JSON.stringify(elem)+"' id='"+elem.id+"' name='"+elem.name+"' value='"+elem.price+"' data-id="+elem.id+" class='sub_chk' /></td><td width='600' >"+elem.name+"</td><td>"+elem.price+"</td><tr>"
);
});
}
});
}
</script>

Updating HTML table using Jquery & ajax

I want to update table data without refreshing the page using Ajax and Jquery.
I know I will need setInterval() method, because I want the table to be refreshed to all users, because multiple users could insert data in to the database and I want to update the table to every user.
I have made a script to send the data from a form without redirecting the user or refreshing the page and then insert it in the database.
MyScript.js
$( document ).ready(function() {
console.log( "Ready!" );
//Submitting from data
$("#submitForm").submit(function(e){
if($('#fName').val() && $('#lName').val() && $('#nickname').val()) {
$.ajax({
type: "POST",
url: "process.php",
data: $("#submitForm").serialize(),
success: function(data){
console.log(data); // show response from the php script.
}
});
}
else {
alert("Please fill the fields.")
}
e.preventDefault();
});
});
In my process.php file I insert the data to the database.
Now I have info.php file that generates my table with all the data and I have a form there to insert new data.
<div id="table" class="col-md-7 ml-5">
<table class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-default">
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nickname</th>
<th>User ID</th>
</tr>
</thead>
<?php $user->showUsers(); ?>
</table>
</div>
the showUsers() function just generate the other rows of the table with the data from SQL.
I have no idea how to refresh the table using Jquery and Ajax.
I tried to use the .load() method, but it also generates the html for my form.
Please help.
As you said, you can use setInterval or better setTimeout since you want the return of the data to trigger a new request later
var tId="";
function getInfo() {
$.get("info.php #table",function(data) {
tId = setTimeout(getInfo,60000);
$("#someContainer").append(data);
});
}
getInfo();

How to get selected data using onChange event using jQuery Data table?

I am working on jQuery Data table to load few data from mysql database.
Here is the html code :
<table id="employee-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>#</th>
<th>User Id</th>
<th>Address</th>
<th>Package Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
jQuery code for jQuery Data Table and My Ajax Request :
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"server_processing.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
}
}
} );
$("#employee-grid").on('change', function() {
var status = $('.changeStatus').val();
alert(status);
$.ajax({
url : "<?php echo SITE_URL . 'toplevel/update-data'; ?>",
data : {
'statusChange' : status
},
type : 'POST',
});
});
});
but When I select the option then every time it's passing first option value
For e.g. This selected option tag has these value :
<option value='1|11' $statusMsg1>Active</option>
<option value='2|11' $statusMsg2>Blocked</option>
It's always passing 1|11 value !! It's should be pass my selected option value. I don't understand why it's happening :(
Change this:
$(".changeStatus").on("change", function(){
var status = $('.changeStatus').val();
alert(status);
// e.t.c...
});
To this:
$(".changeStatus option").change(function(){
var status = $(this).val();
$.ajax({
url: "<?= SITE_URL . 'toplevel/update-data'; ?>",
method: "POST",
data: { statusChange : status },
success: function(data){
alert(status);
}
});
});
Hope it helps!

How to Refresh a dynamic table without refreshing the whole html page

I have a dynamic table that displays data from a mysql database. My database is updated every time in the server. I want to refresh only the table every 2 seconds without refreshing the whole page. How can do this? Please help how accomplish this?.
Parts of my table look like this:
<table id="getdata" border="0" align="left" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#CCFF00">Name</td>
<td bgcolor="#CCFF00">Comment</td>
<td bgcolor="#CCFF00">DatePosted</td>
</tr>
</table>
You will need to use a client-side scripting language such as javascript in order to be able to refresh certain contents on your HTML page. A very common library that is used is jQuery.
PHP
# ajax.php
$contents = '<table class="table table-hover">
<thead>
<tr>
<th>Sound</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bzzz Bzz</td>
</tr>
</tbody>
</table>';
echo json_encode($content);
HTML/Javascript
<button class="refresher">Refresh table</button>
<table id="table-to-refresh">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.refresher', function () {
$.ajax({
url: 'ajax.php',
method: get,
dataType: 'json',
success: function(response) {
$('#table-to-refresh').html(response);
}
});
});
});
</script>
Additional reading
jQuery Docs - Ajax
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('file.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
in file put your full html and php sql code like full code by which you are generating that table.
check this for refrence http://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
Use ajax on an specified time interval like:
$.ajax({
url: 'your_url',
method: get,
data:
{
var1 : val1
},
success: function(response)
{
$('#getdata').html(response); // it will update the html of table body
}
});
just do this:
$.ajax({
contentType: contentType,
dataType: dataType,
type: type,
url: urlGetsearch,
data: '{textvalue: "' + $("#tableId").val() + '" }',
success: function (textvalue) {
$("#tableId").html(htmlData);
},
});
}
The controller is look like this:-
[HttpPost]
public ActionResult Getsearch(string textvalue)
{
your code.....
}

Categories