i Have used following script, data doesn't load to dataTable, i got error click here to show error image
Here my jquery code
Table = $("#example").DataTable({
data:[],
columns: [
{ "data": "Course" },
{ "data": "Batch" },
{ "data": "Admission No" },
{ "data": "Rollno" },
{ "data": "Student Name" },
{ "data": "Email" }
],
rowCallback: function (row, data) {},
filter: false,
info: false,
ordering: false,
processing: true,
retrieve: true
});
$('.view_search_btn').click(function(){
//alert("clicked");
var search_key = $('input[name=view_stu_search]').val();
$('.box-body').show();
$.ajax({
url: "../live_search.php",
type: "post",
data: "key="+'view_student_search_key'+"&search_keyword="+search_key
}).done(function (result) {
Table.clear().draw();
Table.rows.add(result).draw();
}).fail(function (jqXHR, textStatus, errorThrown) {
// needs to implement if it fails
});
});// Click event close here
}); // document close here
and my php code is
if(!ctype_digit($_POST['search_keyword'])){
//echo "given value is string".$_POST['search_keyword'];
$rows = search_keyword($view_student_search_key);
//print_r($rows);
foreach($rows as $row)
{
$query = "SELECT a.stu_rollno, c.stu_course,c.stu_batch,a.admission_no,p.stu_firstname,p.stu_lastname,co.stu_email FROM current_course c, admission_details a,stu_personal_details p, stu_contact_details co WHERE a.stu_rollno = p.stu_rollno AND c.stu_rollno = co.stu_rollno AND a.stu_rollno = c.stu_rollno AND (c.stu_degree = ".$row['degree_id']." AND c.stu_course = ".$row['course_id']." AND c.stu_branch = ".$row['branch_id'].");";
//echo "<br><br>";
$run_query = mysqli_query($con, $query);
while($result = mysqli_fetch_array($run_query))
{
echo "
<tr>
<td>".$row['course_name']."</td>
<td>".$result['stu_batch']."</td>
<td>".$result['admission_no']."</td>
<td>".$result['stu_rollno']."</td>
<td>".$result['stu_firstname'].$result['stu_lastname']."</td>
<td>".$result['stu_email']."</td>
<td align='center'><a href='edit.php?rollno=".$result['stu_rollno']."°ree=".$row['degree_name']."&course=".$row['course_name']."&branch=".$row['branch_name']."' class='btn btn-info btn-sm btn-flat'><i class='fa fa-edit'></i> Edit</a>
<button type='button' class='btn btn-danger btn-sm btn-flat' name='remove_levels' data-toggle='modal' data-target='.bs-example-modal-sm'><i class='fa fa-close'></i> Delete</button>
</td>
</tr>
";
}
}
}`
this following function inside my php
function search_keyword($view_student_search_key)
{
$query = "SELECT d.degree_id,d.degree_name,c.course_id,c.course_name,b.branch_id,b.branch_name FROM degree d,courses c,branch b WHERE d.degree_id = c.degree_id AND b.course_id = c.course_id AND (d.degree_name like '%$view_student_search_key%' OR c.course_name like '%$view_student_search_key%' OR b.branch_name like '%$view_student_search_key%')";
global $con;
$run_query = mysqli_query($con, $query);
//Declare the rows to an array
$rows = array();
// Insert Each row to an array
while($row = mysqli_fetch_array($run_query))
{
$rows[] = $row;
}
// Return the array
return $rows;
}`
Here, You are adding total 6 td for header and Then for inner tr You are adding 7 td. So there is mismatch in datatable td for each row.
What you can do is:
Just add one more td to your datatable initialization preceding with , (comma):
{ "data": "Actions" }
Note: Action is a title for td of edit & other icons column.
Use xhr.dt and reload data using the datatables load() api.
xhr.dt will listen on the ajax call data when it gets loaded. You can clear and draw i.e append data in the xhr callback function. Hope that helps.
Related
I have a random issue while trying to reorder items in a JSON array via JS/PHP, this occurs when the array has more than 1000 items.
Example of my Users.json file:
[
{
"ID_id": "123abc",
"ST_username": "johndoe",
"ST_email": "j#example.com",
"ST_fullname": "John Doe",
},
{
"ID_id": "def345",
"ST_username": "sarahdoe",
"ST_email": "s#example.com",
"ST_fullname": "Sarah Doe",
},
{
"ID_id": "fgh567g",
"ST_username": "markdoe",
"ST_email": "mark#example.com",
"ST_fullname": "Mark Doe",
}
// + additional 1000 similar items in this array
]
So, first of all, I get the JSON file's data and decode it into a PHP array:
$tableName = $_GET['tableName']; // Lets' say $tableName is 'Users'
// fetch data from 'Users.json'
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);
Then I call this function in JS:
function reorderTableData() {
var newOrderArray = [];
var data_arrayStr = JSON.stringify(<?php echo json_encode($data_array) ?>);
var jsonData = JSON.parse(data_arrayStr);
var reorderedData = JSON.stringify(jsonData, newOrderArray);
$.ajax({
url : "reorder-table-data.php",
type: 'POST',
data: 'tableName='+'<?php echo $tableName ?>'+'&reorderedData='+encodeURIComponent(reorderedData),
success: function(data) {
location.reload();
// error
}, error: function(e) {
}});
}
}
My reorder-table-data.php code:
$tableName = $_POST['tableName'];
$reorderedData = $_POST['reorderedData'];
$data_array = json_decode($reorderedData, true);
// Encode back to JSON
$data = json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents($tableName. '.json', $data);
// echo JSON object
echo json_encode($data);
?>
Sometimes this code erases everything and all you see is null in the Users.json file, all data got lost.
What am I doing wrong?
I want to populate a jQuery datatable based on the content of a textarea. Note: my datatables implementation is not serverside. That is: sorting/filtering happens on the client.
I know my php works as it returns expected results in my test scenario (see below). I have included a lot of code to provide context. I am new to datatables and php.
My html looks like this:
// DataTable Initialization
// (no ajax yet)
$('#selectedEmails').DataTable({
select: {
sytle: 'multiple',
items: 'row'
},
paging: false,
scrollY: '60vh',
scrollCollapse: true,
columns: [
{data: "CONICAL_NAME"},
{data: "EMAIL_ADDRESS"}
]
});
// javascript that defines the ajax (called by textarea 'onfocus' event)
function getEmails(componentID) {
deselectTabs();
assignedEmails = document.getElementById(componentID).value.toUpperCase().split(",");
alert(JSON.stringify(assignedEmails)); //returns expected json
document.getElementById('email').style.display = "block";
//emailTable = $('#selectedEmails').DataTable();
try {
$('#selectedEmails').DataTable().ajax =
{
url: "php/email.php",
contentType: "application/json",
type: "POST",
data: JSON.stringify(assignedEmails)
};
$('#selectedEmails').DataTable().ajax.reload();
} catch (err) {
alert(err.message); //I get CANNOT SET PROPERTY 'DATA' OF null
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- table skeleton -->
<table id="selectedEmails" class="display" style="width: 100%">
<thead>
<tr>
<th colspan='2'>SELECTED ADDRESSES</th>
</tr>
<tr>
<th>Conical Name</th>
<th>Email Address</th>
</tr>
</thead>
</table>
<!-- textarea definition -->
<textarea id='distribution' name='distribution' rows='3'
style='width: 100%' onblur="validateEmail('INFO_DISTRIBUTION', 'distribution');"
onfocus="getEmails('distribution');">
</textarea>
The following code returns the expected json:
var url = "php/email.php";
emailList = ["someone#mycompany.com","someoneelse#mycompany.com"];
fetch(url, {
method: 'post',
body: JSON.stringify(emailList),
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
return response.text();
}).then(function (text) {
alert( JSON.stringify( JSON.parse(text))); //expencted json
}).catch(function (error) {
alert(error);
});
php code:
require "openDB.php";
if (!$ora) {
$rowsx = array();
$rowx = array("CONICAL_NAME" => "COULD NOT CONNECT", "EMAIL_ADDRESS" => "");
$rowsx[0] = $rowx;
echo json_encode($rowsx);
} else {
//basic query
$query = "SELECT CONICAL_NAME, EMAIL_ADDRESS "
. "FROM SCRPT_APP.BCBSM_PEOPLE "
. "WHERE KEY_EMAIL LIKE '%#MYCOMANY.COM' ";
//alter query to get specified entries if first entry is not 'everybody'
if ($emailList[0]!='everybody') {
$p = 0;
$parameters = array();
foreach ($emailList as $email) {
$parmName = ":email" . $p;
$parmValue = strtoupper(trim($email));
$parameters[$p] = array($parmName,$parmValue);
$p++;
}
$p0=0;
$query = $query . "AND KEY_EMAIL IN (";
foreach ($parameters as $parameter) {
if ($p0 >0) {
$query = $query.",";
}
$query = $query.$parameter[0];
$p0++;
}
$query = $query . ") ";
$query = $query . "ORDER BY CONICAL_NAME";
$getEmails = oci_parse($ora, $query);
foreach ($parameters as $parameter) {
oci_bind_by_name($getEmails, $parameter[0], $parameter[1]);
}
}
oci_execute($getEmails);
$row_num = 0;
try {
while (( $row = oci_fetch_array($getEmails, OCI_ASSOC + OCI_RETURN_NULLS)) != false) {
$rows[$row_num] = $row;
$row_num++;
}
$jsonEmails = json_encode($rows, JSON_INVALID_UTF8_IGNORE);
if (json_last_error() != 0) {
echo json_last_error();
}
} catch (Exception $ex) {
echo $ex;
}
echo $jsonEmails;
oci_free_statement($getEmails);
oci_close($ora);
}
Looking at a couple of examples on the DataTables site, I found I was making this more difficult than it needed to be: Here is my solution:
HTML: (unchanged)
<table id="selectedEmails" class="display" style="width: 100%">
<thead>
<tr>
<th colspan='2'>SELECTED ADDRESSES</th>
</tr>
<tr>
<th>Conical Name</th>
<th>Email Address</th>
</tr>
</thead>
</table>
<textarea id='distribution' name='distribution' rows='3'
style='width: 100%'
onblur="validateEmail('INFO_DISTRIBUTION', 'distribution');"
onfocus="getEmailsForTextBox('distribution');">
</textarea>
javascript:
Note: The key was the function for data: which returns json. (My php code expects json as input, and of course, outputs json).
[initialization]
var textbox = 'developer'; //global variable of id of textbox so datatables can use different textboxes to populate table
$(document).ready(function () {
$('#selectedEmails').DataTable({
select: {
sytle: 'multiple',
items: 'row'
},
ajax: {
url: "php/emailForList.php",
contentType: "application/json",
type: "post",
data: function (d) {
return JSON.stringify(document.getElementById(textbox).value.toUpperCase().split(","));
},
dataSrc: ""
},
paging: false,
scrollY: '60vh',
scrollCollapse: true,
columns: [
{data: "CONICAL_NAME"},
{data: "EMAIL_ADDRESS"}
]
});
});
[code that redraws table]
function getEmailsForTextBox(componentID) {
deselectTabs();
document.getElementById('email').style.display = "block";
textbox = componentID; //textbox is global variable that DataTable uses as source control
$('#selectedEmails').DataTable().ajax.reload();
}
I have a mysql table with about 30000 rows. I have to put all rows in a DataTable and load each segment each time a table page is loaded (when you click on pagination). I saw that I can use the deferLoading parameter in my JS, but when I use it my pages are not loading. As you can see, I have to load images, so I absolutely have to do a light loading of the content...
Here is my HTML :
<table class="table table-striped table-bordered table-hover datatable products-datatable">
<thead>
<tr>
<th></th>
<th><?=_("Product")?></th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th><?=_("Product")?></th>
<th></th>
</tr>
</tfoot>
</table>
Here is my JS :
var table = $('.products-datatable').dataTable( {
"order": [[ 1, "asc" ]],
"processing": true,
"serverSide": true,
"deferLoading": 30000,
"ajax": {
url: location.protocol + '//' + location.hostname + '/ajax/products.php?action=list',
type: "POST"
},
"columns": [
{ "data": "image",
"orderable": false,
"width": "80px" },
{ "data": "product" },
{ "data": "action",
"orderable": false,
"width": "20px",
"sClass": "class",
}
]
});
Here is my AJAX :
$req = $pdo->prepare('SELECT product_id, name FROM products');
if ( $req->execute() ) {
if ($req->rowCount()) {
$result['draw'] = 1;
$result['recordsTotal'] = $req->rowCount();
$result['recordsFiltered'] = 10;
$result['data'] = array();
$result['DT_RowId'][] = array();
while( $row = $req->fetch() ) {
if ($row['name']) { $name = $row['name']; } else { $name = "N/A"; }
$result['data'][] = array( "DT_RowId" => $row['product_id'],
"DT_RowClass" => 'myclass',
"image" => '<img src="' . HOSTNAME.'assets/img/products/' . $row['product_id'] . '.jpg" class="product_thumb">',
"product" => '' . $name . '',
"action" => "<i class=\"fa fa-close fa-2x text-danger\"></i>"
);
}
}
}
$req->closeCursor();
I'm sure there is something I missed... :-(
I believe you don't need to use deferLoading to benefit from server-side processing.
Your current script just returns all records and doesn't do sorting or filtering. You need to use ssp.class.php (available in DataTables distribution package) or emran/ssp class to correctly handle AJAX requests on the server.
DataTables library will send start and length parameters in AJAX request indicating which portion of the data is needed and your server-side processing class will correctly handle it for you.
Please see an example of server-side processing for more information.
I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.
I try to understand how it work. At the beginning, I was using inside my html code a php array with db and after that I was extracting my array inside my playlist.
Here the example:
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$row['emplacement'] = str_replace("../", "../../", $row['emplacement']);
$row['poster'] = str_replace("../", "../../", $row['poster']);
$row['duration'] = str_replace("00:", "", $row['duration']);
$info = '{artist:"'.$row['artiste'].'", title:"'.$row['track'].'", album:"'.$row['album'].'", mp3:"'.$row['emplacement'].'", cover:"'.$row['poster'].'", duration:"'.$row['duration'].'"}';
array_push($fileinfo, $info);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(
[
<?php
//for each file in directory
$arrlength=count($fileinfo);
for($x=0;$x<$arrlength;$x++)
{
if ($x < ($arrlength - 1))
{
echo $fileinfo[$x].",\n\t\t";
}else
{
echo $fileinfo[$x]."\n\t\t";
}
}
//the result look like this:
//{artist:"Boy Sets Fire", title:"After the Eulogy", album:"After The Eulogy",
mp3:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/01_After_the_Eulogy-JAH.mp3",
cover:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/Folder.jpg", duration:"03:31"},
?>
],
To use everything more dynamically, I try to use JSON with PHP inside my javascript
And my code look like this:
var sourceplayer =
{
datatype: "json",
datafields: [
{ name: 'artiste' },
{ name: 'title' },
{ name: 'album' },
{ name: 'mp3' },
{ name: 'cover' },
{ name: 'duration' }
],
url: 'player.php'
};
$('#player').ttwMusicPlayer(
[
],
So afert url: 'player.php', I don't know how to work with result. It's an array of data like this: "Rows":[{"no_track":"1","track":"Grandma Dynamite","artiste":"24-7 Spyz","album":"Harder Than You","genre":"Alternative","year":"1989","duration":"00:03:44"}
And I want to use it inside the bracket of $('#player').ttwMusicPlayer(
Please give me a cue or an simple example to help me with this. I'm not using pure jplayer but a similar one.
Thanks in advance
Regards,
Eric
PHP json_encode - http://us2.php.net/json_encode
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$fileinfo[] = array(
'mp3' => str_replace("../", "../../", $row['emplacement']),
'cover' => str_replace("../", "../../", $row['poster']),
'duration' => str_replace("00:", "", $row['duration']),
'artist' => $row['artiste'],
'title' => $row['track'],
'album' => $row['album']
);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(<?php echo json_encode($fileinfo); ?>);