how to assign php variable value to a javascript variable [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 4 years ago.
I am trying to pass a value from a php variable to a javascript variable. So instead of defining manually each time {"data": "Country"},{"data": "Customer Name"}... as you see below
<script type="text/javascript">
$(document).ready(function () {
$('#users').DataTable({
"columns": [
{"data": "Country"},
{"data": "Customer Name"},
{"data": "Order Number"},
{"data": "Address"}
],
"processing": true,
"serverSide": true,
"ajax": {
url: 'demo2.php',
type: 'POST'
}
});
});
</script>
Let's say I have a php variabe defined on the top of my html as below
<?php
$jsColumns = '{"data": "Country"},{"data": "Customer Name"},{"data": "Order Number"},{"data": "Address"}';
?>
I want to insert this php variable inside my script
$('#users').DataTable({
"columns": [
<?php echo $jsColumns;?>
],
"processing": true,
"serverSide": true,
"ajax": {
url: 'demo2.php',
type: 'POST'
}
});
It's not working inside the script but when i use echo $jsColumns; on the top in the php part i can see that the variable contains value.
Any idea please what i am missing in my code ? Thank you very much.

What you are doing looks right, but special characters in your actual data may be causing problems, and will be insecure. You could make an array of data, and then use json_encode to escape it - e.g.
<?php
$jsColumns = array(
array('data'=>'Country'),
array('data'=>'Customer Name'),
array('data'=>'Order Number'),
array('data'=>'Address')
);
?>
then
$('#users').DataTable({
"columns": <?php echo json_encode($jsColumns); ?>,
"processing": true,
"serverSide": true,
"ajax": {
url: 'demo2.php',
type: 'POST'
}
});

Related

Jquery Data tables Date format [duplicate]

This question already has answers here:
ASP.NET MVC JsonResult Date Format
(25 answers)
Closed 3 years ago.
I am trying to pull date in my data tables but for some reason the format of the data is not correct. I am getting the data from a stored procedure.
Original:
/Date(1575612000000)/
Expected Output:
01-15-2020
Code example:
$(document).ready(function () {
var mesa = $('.datatable').DataTable({
filename: "LocationCodes",
responsive: true,
"bAutoWidth": false, // toggle this depending on how wide you want the table
"ajax": {
"url": "/controller/sp",
"type": "GET",
"datatype": "json"
},
"deferRender": true,
"responsive": true,
dom: 'Bfrtip',
"bSort": false,
buttons: [
'excel', 'print'
],
"columns": [
{ "data": "FileName" },
{ "data": "ProjectName" },
{ "data": "RecordInsertTime" }
]
Thanks,
Minhal
is this what you want?
var d = new Date(1575612000000);
let month=d.getMonth()+1 // 12
let date=d.getDate() // 6
let year=d.getFullYear()
console.log(`${date}-${month}-${year}`)

jQuery selector won't work with Datatables

hey guys i have a problem with Datatable plugin
the problem is that i can't select the checkbox in the action column to convert it into bootstrap-toggle
it was working before but when i use the serverside of datatable and declare the checkbox in the controller nothing works (Sorry for my english )
please help!!
this is the controller code
return DataTables::of($participant)
->addColumn('action',function($participant){
$route = route('admin.participant.presence',$participant);
return '<form action="'.$route.'" method="PATCH">
<input type="hidden" name="presence" value="0">
<input type="checkbox" class="participation" onchange="this.form.submit()" '.isChecked($participant).' name="presence" value="1">
</form>';
})->make(true);
and here's the js code in the view and I think the problem comes from here
<script>
$(document).ready( function(){
var id = {{request()->route('id')}};
$('#table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "/admin/evenment/event/participant/ajaxdatatable/"+id,
"columns":[
{"data": "adherent_id"},
{"data": "nom_participant"},
{"data": "prenom_participant"},
{"data": "fonction"},
{"data": "action"},
]
});
$('.participation').bootstrapToggle({
on: 'Oui',
off: 'Non',
onstyle: 'success',
offstyle: 'danger',
width: '70'
});
});
</script>
When using serverSide, the resulting table is displayed after the full page load. Therefore the bootstrap elements have already been generated when datatable displays the results.
You can solve this by calling a function which takes care of displaying bootstrap elements in the "complete" ajax handler. (here the $.extend applies to a datatable options object)
$.extend(true, options, {
"ajax": {
"url": self.data('url'),
"data": function ( d ) {
d.action = "drawDatatable"
},
"type": "POST",
"complete": function() {
prepareDisplayElements("#"+self.attr("id"));
}
}
});
So in your case this could be something simple like this:
$(document).ready( function(){
var id = {{request()->route('id')}};
$('#table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/admin/evenment/event/participant/ajaxdatatable/"+id,
"complete": function() {
$('.participation').bootstrapToggle({
on: 'Oui',
off: 'Non',
onstyle: 'success',
offstyle: 'danger',
width: '70'
});
}
},
"columns":[
{"data": "adherent_id"},
{"data": "nom_participant"},
{"data": "prenom_participant"},
{"data": "fonction"},
{"data": "action"},
]
});
});

Ellipsis render for Datables [duplicate]

This question already has answers here:
how to use Jquery Datatables Ellipsis renderer for template field link button?
(1 answer)
Solution for Ellipsis - Jquery + Bootstrap + Datatables
(1 answer)
DataTables how to cut string and add (...) and put the full string in tooltip
(2 answers)
Closed 4 years ago.
I'm working on a CI project that requires the use of datatables, some of the content in the database has a large number of characters and i want to limit those to 150, i have tried to use the examples that are posted in the datatables site without luck, just to be clear i didnĀ“t made this full script, I took it from somewhere else.
This is my script
<script type="text/javascript">
$(document).ready(function() {
var st = $('#search_type').val();
var table = $('#consulta-table').DataTable({
"dom" : "<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
"processing": false,
"pagingType" : "full_numbers",
"pageLength" : 15,
"serverSide": true,
"orderMulti": false,
"order": [
<?php if($default_order != null) : ?>
[<?php echo $default_order ?>, "<?php echo $default_order_type ?>"]
<?php else : ?>
[6, "desc"]
<?php endif; ?>
],
"columns": [
null,
null,
null,
null,
null,
{ "orderable": false },
{ "orderable": false },
null,
{ "orderable": false }
],
"ajax": {
url : "<?php echo site_url("consultas/consultas_page/" . $page . "/" . $catid) ?>",
type : 'GET',
data : function ( d ) {
d.search_type = $('#search_type').val();
}
},
"drawCallback": function(settings, json) {
$('[data-toggle="tooltip"]').tooltip();
}
});
$('#form-search-input').on('keyup change', function () {
table.search(this.value).draw();
});
} );
function change_search(search)
{
var options = [
"search-like",
"search-exact",
"title-exact",
"title2-exact",
"title3-exact",
"title4-exact",
"title5-exact",
"title6-exact",
];
set_search_icon(options[search], options);
$('#search_type').val(search);
$( "#form-search-input" ).trigger( "change" );
}
function set_search_icon(icon, options)
{
for(var i = 0; i<options.length;i++) {
if(options[i] == icon) {
$('#' + icon).fadeIn(10);
} else {
$('#' + options[i]).fadeOut(10);
}
}
}
</script>
Any help is appreciated
Thanks in advance
Have you tried this yet? It is the official plugin offered by people under the datatables.net community. You just need to follow the instruction there and you're good to go.
Simply download/copy the plugin script then, follow this sample code
$('#myTable').DataTable( {
columnDefs: [ {
targets: 0,
render: $.fn.dataTable.render.ellipsis()
} ]} );

Send Data from Cassandra to DataTables (NoSQL)

Hey Guys I have a problem. I`m new to Cassandra and DataTables and my task is to send data from our 'Cassandra-Server' to the Table plug-in 'DataTables'.
I was looking for some examples or tutorials but I never found one for Cassandra-NoSQL.
I tried the following and this Error is always occurring:
PHP:
//setting header to json
header('Content-Type: application/json');
include 'connect.php';
$statement = new Cassandra\SimpleStatement("SELECT * FROM table1");
$result = $session->execute($statement);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
JS:
$(document).ready(function () {
'use strict';
var table = $('#main').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "php/server-side.php",
"type": "GET"
},
"columns": [
{ "data": "name" },
{ "data": "type1" },
{ "data": "type2" },
{ "data": "type3" },
{ "data": "land" },
{
"data": "id",
"orderable": false
}
],
"order": [[0, 'asc']]
});
});
Error:
*Uncaught TypeError: Cannot read property 'length' of undefined
jquery.dataTables.min.js: 39*
I think DataTables don't know what to do with the information (json/$data).
In this example https://datatables.net/examples/data_sources/server_side.html
sspclass.php is used but it is written in SQL so no use for me =(
Can somebody help me with this specific problem?

datatables columnDefs not working: jquery / javascript

My datatable loads perfectly except the columndefs do not work.
Anybody got a clue?
Please help. I just want to add a click event to every cell in column 1. I get no errors either.
It works in this example on the end column...https://datatables.net/examples/ajax/null_data_source.html
var table = $mytable.DataTable( {
"serverSide": true,
"ajax": {
"url": url_string,
"cache": true,
"columnDefs": [
{"targets": 1,"data": null,"defaultContent": "<button>Select Image ID</button>"} ,
]
},
});
Found a great post on stack overflow that really helped.
and changed it to suit me this is the post Edit jQuery Datatable fields
And here is what I have working for me. I was concentrating too much on the API and less on just Jquery. The trick was execute the jquery after "drawCallback":
Credit to #Jeromy French
var table = $spr_cnt_tbl.DataTable( {
"serverSide": true,
"ajax": {
"url": url_string,
"cache": true,
"columnDefs": [
{"targets": 1,"data": null,"defaultContent": "<button>Select Image ID</button>"} ,
]
},
"drawCallback": function( settings ) {
apply_label();
}
});
var apply_label=function(){
$spr_cnt_tbl.find("td:nth-child(2)").not(':has(.label)').each(function(){
if( this.innerHTML===""){
$(this).wrapInner("<button class=btn btn-success id='sel_img' type='button'>Select Image</button>");
}
else {
$(this).wrapInner('<span class="label label-success"></span>');
}
});
};
});
});

Categories