Initialize dataTable from separate .php table - php

I am trying to initialize a dataTable from a separate .php file that builds a table. It builds the table okay, but the dataTable properties do not seem to be in effect.
Here is my code:
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#live_table').load("table.php");
var refreshId = setInterval(function() {
$('#live_table').load("table.php");
}, 2000);
$.ajaxSetup({ cache: false });
$('#data').dataTable();
});
</script>
<title></title>
</head>
<body>
<div id="live_table">
</div>
</body>
</html>
table.php
<table id="data">
<thead>
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
index.php is meant to refresh the table every 2000ms and table.php is actually more complex in my real situation and requires conditional cell backgrounds and links which is why I didn't choose to use the server side processing (JSON) for table data.
Any idea why the $('#data').dataTable(); command isn't working?

I think it is not loading because you are using a selector that does not exist yet.
Try:
$(document).ready(function() {
$('#live_table').load("table.php");
var refreshId = setInterval(function() {
$('#live_table').load("table.php");
}, 2000);
$.ajaxSetup({ cache: false });
$('#data').dataTable(); //This line should be in table.php
Technically there is no element #data in the DOM. You should put the table initialization in the table.php file.

It looks like the problem is the call to .dataTable() is occurring before the table is actually loaded, since .load call happens asynchronously and the rest of the code keeps running. You need to call .dataTable() after the request has finished by using the third parameter to .load:
$('#live_table').load(
"table.php",
{},
function() { $('#data').dataTable(); }
);
Demo: http://jsfiddle.net/sAnUL/1/

you can use callback function of load() method:
$('#live_table').load("table.php", function(){
$('#data').dataTable();
});
or use ajaxSuccess():
Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.
$('#data').ajaxSuccess(function(){
$(this).dataTable()
})

Related

Table not sorting through PHP but sorting inside HTML

I have html table create by a php, I want to sort this table, but no success.
If I create the table inside the html the sort work.
<!DOCTYPE html>
<html>
<head>
<title>Teste</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
<div class="container mb-3 mt-3" id="inicio">
</div>
<script>
$(document).ready(function(){
load_list();
$('.mydatatable').DataTable();
function load_list()
{
var action = "data";
$.ajax({
url: "teste.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#inicio').html(data);
}
})
}
});
</script>
</body>
</html>
Example of table from php:
<?php
if(isset($_POST["action"]))
{
if($_POST["action"]=="data")
{
$output = '
<table class="table table-striped table-bordered mydatatable" style="width: 100%">
<thead>
<tr>
<th>Tittle</th>
</tr>
</thead>
<tbody>
<tr>
<td>data</td>
</tr>
<tr>
<td>date2</td>
</tr>
</tbody>
</table>
';
echo $output;
}
?>
I think the $('.mydatatable').DataTable(); is in the wrong place, I tried my options but only work if the table is inside the html page. Anyone can help me?
As first A in ajax means asynchronous, then your call to $('.mydatatable').DataTable(); happens before real data is loaded via ajax. You should move call to DataTable to success callback:
success:function(data)
{
// note the order - first you load `html`
$('#inicio').html(data);
// after that you have a `.mydatatable` selector available
$('.mydatatable').DataTable();
}
Table html is not there when you initialize your Datatable.
$(document).ready(function(){
load_list();
function load_list()
{
var action = "data";
$.ajax({
url: "teste.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#inicio').html(data);
//move this to here
$('.mydatatable').DataTable();
}
})
}

Make Each Row of DataTables a Hyperlink to ID

I've tried the other solutions but been unable to make it work.
How do I make each row of DataTables a hyperlink to its ENSG ID?
I've tried to do it outside the Ajax interface.
<!DOCTYPE html>
<html>
<title>Datatable Demo1 | CoderExample</title>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
var dataTable = $('#gene-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"gene-grid-data.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".gene-grid-error").html("");
$("#gene-grid").append('<tbody class="gene-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#gene-grid_processing").css("display","none");
}
}
} );
} );
</script>
</head>
<body>
<div class="container">
<table id="gene-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>ENSG ID</th>
<th>Gene</th>
<th>Biotype</th>
</tr>
</thead>
</table>
</div>
</body>
I would store the id of the row in a data attribute and then write a click handler to do this... Just remember though, datatables creates dynamic html so if setting a click event for something that is getting destroyed and redrawn, you will need to attach the handler to a parent element. I usually use the body element.
//add this option to datatables initialization
//this will add a data attribute containing the id
//to each row in table.
"rowCallback": function( row, data ) {
$(row).data('id',data.ID);
}
//handler to redirect to detail page...
$('body').on('click', 'tr', function(){
window.location = "http://svr/app/controller/action/" + $(this).data('id');
});

How to read content from td with simple html dom

This is my code:
<tr>
<td class="text">
<div>Something</div>
</td>
<td>Something2</td>
<td>Something3</td>
</tr>
I want to get content from td and return in single line like this
Something - Something2
For HTML DOM manipulation there is a library called jQuery you can easily Travers the HTML dome with that.
and Bellow is the solution of your problem.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table id="tblNewAttendees">
<tr>
<td class="text"><div>Something</div</td>
<td>Something2</td>
<td>Something3</td>
</tr>
</table>
<div class="table-content"></div>
<script>
$(document).ready(function(){
var content ='';
$('#tblNewAttendees tr').each(function() {
$.each(this.cells, function(){
//alert($(this).text());
content+=$(this).text()+" - ";
});
});
$(".table-content").html(content);
});
</script>
</body>
</html>

I want jquery popup should come once the form is submitted using php and mysql, the output has come in jquery popup

I want jquery popup should come once the form is submitted using php and mysql, the output has come in jquery popup?I have fetched the values from table.Those value I have to show in pop?what kind of pop is available for that?
This is the value I want to show in popup?once the form is submitted.Those values are from db?
Here is the db values:
id Author Names Title of the Paper Journal Vol Yr Pages
1 V.Thahira Banu Assistant Semantic Sensor Network A Survey International Special Volume 2013 p.no:549 to 553
Professor, PSGR Krishna..
2 .......................
3 .......................
jQuery by itself has no UI elements. You either have to use the traditional javascript alert() or include a UI library like jQueryUI and use their dialog component or equivalent.
You can use JavaScript Alert or a plugin for that.
JavaScript Alert
Alert(data);
of visit this link Sample Alert Plugins for use of plugins
This is the best thing, you should use and try :- http://getbootstrap.com/javascript/#modals
Check the code:
Index.php
<?php
require_once"class/db.php";
$db= new db();
$data=$db->fetch_user_det();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Animation</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery- ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
});
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>
<table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Name</td>
<td>Class</td>
<td>Roll</td>
</tr>
<?php
foreach($data as $val)
{
?>
<tr>
<td><?php echo $val['field_name1']; ?></td>
<td><?php echo $val['field_name2']; ?></td>
<td><?php echo $val['field_name3']; ?></td>
</tr>
<?php
}
?></table>
</p>
</div>
<button id="opener">Open Dialog</button>
</body>
</html>
Database Class: db.php
you can download full project from here: http://1drv.ms/OzfdH4
just edit database details in db.php
check updated link

Access JavaScript variables value in php to store in mysql

Just simple,
I am trying to access the variable in javascript inside the php while working with elrte,
bleow is my index.php file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>One textarea with elRTE and file upload plus one text field with elFinder</title>
<!-- jQuery and jQuery UI -->
<script src="js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery-ui-1.8.7.custom.min.js" type="text/javascript" charset="utf- 8"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.7.custom.css" type="text/css" media="screen" charset="utf-8">
<!-- elRTE -->
<script src="js/elrte.min.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="css/elrte.min.css" type="text/css" media="screen" charset="utf-8">
<link rel="stylesheet" href="css/elrte.full.css" type="text/css" media="screen" charset="utf-8">
<!-- elFinder -->
<link rel="stylesheet" href="css/elfinder.css" type="text/css" media="screen" charset="utf-8" />
<script src="js/elfinder.full.js" type="text/javascript" charset="utf-8"></script>
<!-- elRTE and elFinder translation messages -->
<!--<script src="js/i18n/elrte.ru.js" type="text/javascript" charset="utf-8"></script>
<script src="js/i18n/elfinder.ru.js" type="text/javascript" charset="utf-8"></script>-->
<script type="text/javascript" charset="utf-8">
// elRTE with elFinder on a textarea
$().ready(function() {
var opts = {
cssClass : 'el-rte',
lang : 'en', // Set your language
allowSource : 1,
height : 450,
toolbar : 'maxi', // 'tiny', 'compact', 'normal', 'complete', 'maxi', or 'custom' (see advanced documentation for 'custom')
cssfiles : ['css/elrte-inner.css'],
fmAllow : 1,
fmOpen : function(callback) {
$('<div id="myelfinder" />').elfinder({
url : 'connectors/php/connector.php',
places : '',
lang : 'en', // Set your language
dialog : { width : 900, modal : true, title : 'Files' }, // Open in dialog window
closeOnEditorCallback : true, // Close after file select
editorCallback : callback // Pass callback to file manager
})
}
}
$('#editor').elrte(opts);
// Text field with elFinder
var opt = {
url : 'connectors/php/connector.php',
places : '',
lang : 'en',
editorCallback : function(url) {document.getElementById('field').value=url;}, // The id of the field we want elfinder to return a value to.
closeOnEditorCallback : true,
docked : false,
dialog : { title : 'File Manager', height: 500 },
}
$('#open').click(function() { // The id of the button that opens elfinder
$('#finder').elfinder(opt) // The id of the div that elfinder will open in
$('#finder').elfinder($(this).attr('id')); // it also has to be entered here.
})
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
});
})
})
</script>
</head>
<body>
<?php
$q=mysql_query("select * from aw_about_us")or die(mysql_error());
$r=mysql_fetch_array($q);
extract($r);
?>
<div id="finder"></div>
<table cellpadding="5" cellspacing="5" border="0" width="100%">
<form name="feedback" id="frm" method="post">
<tr>
<td>Title : </td>
<td><input type="text" id="atitle" size="75" value="<?=$abt_title?>"></td>
</tr>
<tr>
<td>Tag Line : </td>
<td><input type="text" id="atag" size="75" value="<?=$abt_small_line?>"></td>
</tr>
<tr>
<td colspan="2"><textarea id="editor" id="acontent" cols="50" rows="4">
<?=$abt_content?>
</textarea></td>
</tr>
<!--<input type="text" id="field" name="field" size="60"/> -->
<!--<input type="button" id="open" value="Browse..." /><br>-->
<tr>
<td><input type="submit" id="btnsub" value="Submit"></td>
</tr>
</form>
</table>
<?php
/*echo $_GET['val'];
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
*/?>
</body>
</html>
I am able to get the value of elrte inside the javascript variable, but now I wanted store this value inside the mysql database, as I am using PHP I want to access this value inside a php so that I can store it in database,
I tried using window.open("abc.php?val="+content); but the value is very large so get method cannot be acceptable here, so is there any way to get this value inside the php? or any alternate way to do this?
** Edit :**
Now it gives me a value of content variable after making following changes, but I want all 3 variables, but unable to get
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
var title = document.getElementById('atitle').val;
var tag = document.getElementById('atag').val;
alert('title'+title);
$.ajax({
type: "POST",
url: 'abc.php',
data: {title : title, tag : tag, content : content},
success: function(html) { $('result').append(html); },
dataType: 'html'
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
and php file
<?php
include('inc/conn.php');
if(isset($_POST['updabt']))
{
$cont=$_POST['updabt'];
$q1=mysql_query("update aw_about_us set abt_title='$title', abt_small_line='$tag', abt_content='$cont'") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
Now how to get all three variables??
You'll need to submit the value to your PHP script using a POST request to your server. You can do this with Ajax requests, and I believe jQuery has built-in methods for Ajax which are cross-browser.
You need 2 pages, one which will send AJAX (this you have) and one wich will respond (below):
<?php
///ajax.php
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
In javascript you create AJAX post
data['updabt'] = '';
$.ajax({
type: "POST",
url: 'ajax.php',
data: data,
success: function(html) { $('result').append(html); },
dataType: 'html'
});
You can use AJAX (easiest with a library such as jQuery) to submit the variables to another PHP script that will INSERT the values to your database.
Start by reading the following...
jQuery.ajax
jQuery.post
This is actually very simple once you get your head around the subtleties of AJAX.
Here is a simple example to get you off and running. Suppose you wanted to log something to your PHP error log...
This would be my JavaScript function:
var log = function(val) {
$.post("ajax.php", {"mode": 'log', "val": val}, function() {});
}
ajax.php would be a collection of functions, ideally a class...
public function __construct() {
$arrArgs = empty($_GET)?$_POST:$_GET;
/**
* using 'mode' I can send the AJAX request to the right method,
* and therefore have any number of calls using the same class
*/
if (array_key_exists('mode', $arrArgs)) {
$strMethod = $arrArgs['mode'];
unset($arrArgs['mode']);
$this->$strMethod($arrArgs);
}
}
protected function log($arrArgs) {
error_log($arrArgs['val']);
}
The same idea can easily be adapted to write data to a database.

Categories