Showing 0 entries datatable - javascript

I'm having a problem in datatable. Why I got a "Showing 0 to 0 of 0 entries", also can't search, it always show "no data available" and the pagination are disabled. What should I do?
Here's my code:
//Show Products Table
function show_products() {
var action = "Show Products";
$.ajax ({
type: 'POST',
url: '../admin/class.php',
data: {action: action},
success: function(data) {
//if success it will display the data
$('#show_products').html(data);
}
});
}
//class.php(data)
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'Show Products':
//call the function show_products();
show_products();
break;
}
}
//Function to fetch the all products
function show_products() {
GLOBAL $db_conn;
$search_query="SELECT p.product_id as productID, p.*, pe.* FROM tblproduct p JOIN (SELECT p.product_id, MIN(pe.product_extension_id) AS product_extension_id FROM tblproduct p LEFT JOIN tblproduct_extension pe ON pe.product_id = p.product_id GROUP BY product_id ORDER BY product_id) product_unique LEFT JOIN tblproduct_extension pe ON pe.product_extension_id = product_unique.product_extension_id WHERE p.product_id =product_unique.product_id";
$query = mysqli_query($db_conn, $search_query);
while($row = mysqli_fetch_array($query)) {
$status = ($row['product_stocks'] == 0) ? '<label class="label label-danger">Out of stocks</label>' : '<label class="label label-success">In stocks</label>';
?>
<tr>
<td><?=$row['product_name']?></td> /*fetch product_name*/
<td><?=$row['product_brand']?></td> /*fetch product_brand*/
<td><?=$row['category_name']?></td> /*fetch category_name*/
<td>₱<?=number_format($row['product_price'], 2)?></td> /*product_price*/
<td><?=$row['product_size']?></td> /*fetch product_size*/
<td><?=$row['product_stocks']?></td> /*fetch product_stocks*/
<td><?=$status?></td> /*display status if 0 stocks "outofstock"*/
</tr>
<?php
}
}
//Script of datatable
$(document).ready(function(){
//get the id of table
$('#datatable1').DataTable();
});
Screenshot:
PS: I included all the libraries.

Initialize your table only after you retrieve the data from the server.
$.ajax ({
type: 'POST',
url: '../admin/class.php',
data: {action: action},
success: function(data) {
// If table is initialized
if ($.fn.DataTable.isDataTable('#datatable1')){
// Destroy existing table
$('#datatable1').DataTable().destroy();
);
//if success it will display the data
$('#show_products').html(data);
// Initialize the table
$('#datatable1').DataTable();
}
});
If you will be making Ajax request multiple times.

$.ajax ({
type: 'POST',
url: '../admin/class.php',
data: {action: action},
success: function(data) {
// If table is initialized
if ($.fn.DataTable.isDataTable('#datatable1')){
// Destroy existing table
$('#datatable1').DataTable().destroy();
};
//if success it will display the data
$('#show_products').html(data);
// Initialize the table
$('#datatable1').DataTable();
}
});
Added some additional formatting

Related

Query duplicates after each onClick

I have an add feature that runs an insert query (using PDO).
The first insert works accordingly. It's the second run, and every run after that causes the query to duplicate times 2.
I have no idea why this is happening.
The user makes a selection, which populates a datatable (example1). They can then select one of the records (or lanes) which populates another datatable (example2).
Here is the initial onClick event:
$('#example1').on('click', 'tr > .laneClick', function(e){
e.preventDefault();
const dataTable = $('#example1').DataTable();
const rowData = dataTable.row($(this).closest('tr')).data();
let partnerCode = rowData['partner_code'];
let partnerName = rowData['partner_name'];
let groupName = rowData['groupname'];
let lanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
groupName: groupName
}
displayLaneRecords(lanecriteria);
});
Here is the function displayLaneRecords, which displays the second datatable called "example2" after the .laneClick onClick event:
function displayLaneRecords(lanecriteria){
if(lanecriteria == ""){
let data = '';
}
else{
let data = {
lanecriteria: {
partnerCode: lanecriteria.partnerCode,
vesselProfile: lanecriteria.vesselProfile,
salesRep: lanecriteria.salesRep
}
}
}
$.ajax({
url: 'api/getLaneData.php',
type: 'POST',
data: data,
dataType: 'html',
success: function(data, textStatus, jqXHR){
var jsonObject = JSON.parse(data);
var table = $('#example2').DataTable({
"data": jsonObject,
"columns": [
// data columns
],
"dom": 'Bfrtip',
"buttons": [
{
text: '<i class="fa fa-plus"></i> Add Lane',
className: 'addLane btn btn-primary btn-sm',
action: function (e, dt, node, config){
// opens the form for processing
$('#addLaneModal').modal('show');
}
}
]
});
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: '+ errorThrown);
return false;
}
}); // end ajaxcall
// here is where the form process will occur
} // end displayLaneRecords();
As you will see, the form process will occur within the displayLaneRecords() function. I had to do this so when the process is complete, I can repopulate the datatable without refreshing.
Here is the form process:
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let partnerCode = $('#addlanepartnercode').val();
let partnerName = $('#addlanepartnername').val();
let groupName = $('#addlanegroupname').val();
let addlanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
groupName: groupName
}
$.post('api/editLane.php', {addlanecriteria:addlanecriteria}, function(data){
if(data.indexOf('Error') > 1){
$('.message').text(data);
$('#errorModal').modal('show');
return false();
}
else{
$('.message').text(data);
$('#messageModal').modal('show');
$('#messageModal').on('hidden.bs.modal', function(){
$("#addLaneModal").modal('hide');
displayLaneRecords(lanecriteria); // call displayLaneRecords to refresh the table
});
}
});
});
The actual PHP process called editLane.php looks like this:
<?php
if(isset($_POST['addlanecriteria'])){
$value = $_POST['addlanecriteria'];
$partnerCode = isset($value['partnerCode']) ? $value['partnerCode'] : '';
$partnerName = isset($value['partnerName']) ? $value['partnerName'] : '';
$groupName = isset($value['groupName']) ? $value['groupName'] : '';
try{
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert = $dbc->prepare("INSERT INTO table (`partner_code`, `partner_name`, `group_name`) VALUES (:newpartnercode, :newpartnername, :newgroupname)");
$insert->execute([
'newpartnercode' => $partnerCode ,
'newpartnername' => $partnerName ,
'newgroupname' => $groupName
]);
if($insert){
echo "Success: New Lane has been added.";
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
?>
I tried to minimize as much code as I could.
All of the above works without any visible errors. When the form is submitted, a new record is inserted into the table, and the datatable refreshes without the page refreshing.
The problem occurs when the user adds another record - the query duplicates, and instead of inserting 1 record, 2 are inserted. If they add another record, the query will insert 4 records.
What can I try next?

Only Some Columns of Table Display after Added to Array in JS and PHP

I am trying to get all columns and rows to appear after being added to an array in JS and PHP. For some reason, neither the player column nor the status column are filled with content. Any insight into this is appreciated.
This is the code where the array is collected:
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$result = $db->query($query);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
?>
And this is the code where the table originates:
var reloadTable = function(data) {
if ($.data(state) == $.data(data)) {
return;
}
$('#js-lobby-table').empty();
$.each(data, function(rowNumber, rowData) {
var row = $('<tr>');
//console.log(data);
// Player
row.append($('<td>', {
'html': data.eName
}));
// Status
row.append($('<td>', {
'html': data.gameID == "000" ? 'waiting' : 'ingame'
}));
// Win %
row.append($('<td>', {
'html': 'TODO'
}));
// Games
row.append($('<td>', {
'html': 'TODO'
}));
// K/D
row.append($('<td>', {
'html': 'TODO'
}));
$('#js-lobby-table').append(row);
});
// Set the current table state.
state = data;
};
setInterval(function() {
$.ajax({
type: 'POST',
url: '/lobby/api/table.php',
data: {
id: '<?= $_GET['
id '] ?>'
},
success: reloadTable,
dataType: 'json'
});
}, 10);
When you debug, look at the values in your variables to ensure they are what you expect them to be. Your code is treating these variables inconsistently. For example, you're looping over data:
$.each(data ...
Which implies that data is an array. But then you also try to access values on data:
'html': data.eName
I suspect that you actually want to access values on rowData within that iteration:
'html': rowData.eName
(Same error a few more lines down in your code.)

how to empty the function parameter once it passes to the function?

I am trying to send the parameter in a function but its in a loop so when i select the same function next time it first send me the previous value then send me the value that i want which causes the function to be empty and not take any value let me show you my code.
$(window).load(function(e) {
loadmore();
select_likes();
select_share();
// get_recieve_friend_requests();
// get_sent_friend_requests();
});
function loadmore() {
var lastID = $('.load-more').attr('lastID');
// alert(lastID);
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("user/get_all_post"); ?>',
data: {
id: lastID
},
dataType: 'json',
beforeSend: function(data) {
$('.load-more').show();
},
success: function(data) {
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json == "") {
$("#bottom").append('<div class="btn btn-default col-md-6" >' + 'No More Results' + '</div>');
$("#Load_more_data").hide();
} else {
$postID = json[json.length - 1].id;
$('.load-more').attr('lastID', $postID);
$.each(json, function(key, data) {
var post_id = data.id;
var post_status = data.status;
var status_image = data.status_image;
var multimage = data.multimage;
if (!post_status == "" && !status_image == "") {
alert(post_id);
$("#status_data").append('<div class="media-body"><div class="input-group"><form action="" id="form_content_multimage"><textarea name="textdata" id="content_comment_multimage" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_multimage" onclick="comment_here_multimage(' + post_id + ');" >Comment</button><?php echo form_close();?></div></div></li></ul></div></div>');
}
});
}
}
});
}
function comment_here_multimage(post_id) {
$(document).on('click', '#comment_button_multimage', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
});
}
The post_id is being passed onclick event of the comment_here_multimage but whenver i click on it after first time same id is being passed again first then the next id passes. what can i fo to empty the post_id value once it completes.
look at these images and tell me if there is something you dont understand.
[![first time comment][1]][1]
[![second time comment][2]][2]
[![second time comment][3]][3]
[1]: https://i.stack.imgur.com/b36o4.png
[2]: https://i.stack.imgur.com/ahg3W.png
[3]: https://i.stack.imgur.com/taHAS.png
Your problem is not isolated in code. However according to my understanding.
You are binding "comment_here_multimage" function on click event of button when creating dynamic html.
Once context is loaded and user clicks that button you again binds another function on same button, which is ultimately added to the event stack.
If user clicks the button first time nothing will happen, there is no action on it. On first time it will register a handler with it.
If user click second time it will fire the handler attached on first click resulting in old postid supplied to it.
I think your problem is with passing parameter. You can set it in a custom parameter and get it later in click handler. Or you can change your handler like below.
You can change your code like this
onclick="comment_here_multimage(this,' + post_id + ');"
function comment_here_multimage(e,post_id) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
;
}

jQuery call with ajax not responding, no error

I have a small problem with a giftlist generated from SQL. My goal is to echo each row as a form with a textbox and a button, then when any button clicked, pass the textbox value, and an id number (hidden field value) to a function. Then this function would have get the values, and sends them with AJAX get method to a php, which would update a row with the giver's name in the SQL database. I cannot find the error in my code, so please help me in this regard.
EDIT: i need to figure out too, how to identify the button which was clicked.
This would be my script:
<script type="text/javascript">
var aname = '';
var tid = 0;
$('.giftok').click(function()
{
if ($('.aname').val() === '')
{
alert('You have not provided your name.');
}
else
{
aname = $('.aname').val();
tid = $('.id').val();
$.ajax
({
url: "kosarba.php",
data: { ganame: aname, tid: gtid },
type: "GET",
context: document.body
}).done(function() {
alert("OK, it works.");
});
alert('Thank you!');
}
});
</script>
Here is my HTML+PHP:
echo "<table id='giftlist' align='center' font-size='10pt'>";
while($sor=mysql_fetch_array($sordb))
{
echo "<tr>
<td width='420px'>$sor[gname]</td>
<td width='65px'>$sor[gprice] Ft</td>";
if (strlen($sor[aname]) !== 0)
{
echo "<td width='200px'>Sorry, someone already bought this one for us.</td>";
}
else
{
echo "<td width='335px'><form id='rendelget'>Your name: <input type='textbox' id='aname' name='aname' value='$aname'/><input type='hidden' class='id' name='id' value='$sor[id]'/> <button type='button' id='$sor[id]' class='giftok' value='Megveszem'>Megveszem</button></form> </td>";
}
echo "</tr>";
}
echo "</table>";
You have mistaken a variable name tid = $('.id').val() tid
should be gtid
I think that would be your script
$(document).ready(function(){
var aname = '';
var tid = 0;
$('.giftok').click(function()
{
if($(this).closest('form').attr('name') == 'myId'){ //or id
if ($('.aname').val() === '')
{
alert('You have not provided your name.');
}
else
{
aname = $('.aname').val();
gtid = $('.id').val();
$.ajax
({
url: "kosarba.php",
data: { ganame: aname, tid: gtid },
type: "GET",
context: document.body
})
.error(function(){
alert('Ajax worked but error form server.');
})
.done(function() {
alert("OK, it works.");
});
alert('Thank you!');
}
}
});
})
//Update: If you identify the form holding the button gitve the form a name or id
Inside the ajax call,
data: { ganame: aname, tid: gtid }
'tid' is the post parameter, while gtid is the javascript variable.
Mistakenly, you have used gtid instead of tid .
use :
data: { ganame: aname, tid: tid }

Ajax call insert

I have 2 ajax calls one to insert data, one to get data. Together with the functions for select and insert. the console log of the ajax call select is empty. However, when i check phpmyadmin the correct value is there.
If i start the game again, there will be 1 value (from previous game) but the score of the actual game isn't there. Until I start the game again. And so on. Does anyone know why the values are in my sql but the ajax call says it's empty?
What I understand from it. There's a score via ajax and in php it will get into the part "Check json" it sees json isn't empty so it goes to InsertScore().
The second ajax is cast but this time it doesn't have json so it will get to the method "GetScores".
The insert happens always before the select so the last score should be seen, I don't understand why it doesn't do that.
Ajax call insert:
$.ajax({
type: "POST",
url: "Database.php",
dataType: "json",
data: { json: jsonData }
});
ajax call select:
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) {
console.log(obj);
stageRef.$("txtTopscorePunt").html(obj[0].Score);
stageRef.$("txtTopscoreNaam1").html(obj[0].Naam);
stageRef.$("txtTopscorePunt2").html(obj[1].Score);
stageRef.$("txtTopscoreNaam2").html(obj[1].Naam);
stageRef.$("txtTopscorePunt3").html(obj[2].Score);
stageRef.$("txtTopscoreNaam3").html(obj[2].Naam);
}
});
php insert:
function InsertScore($obj) {
$query = "INSERT INTO topscoresNew (Score, Naam) VALUES('" . $obj['score'] . "','" . $obj['naam'] . "')";
$result = mysql_query($query);
}
php select:
function GetScores() {
$query = "SELECT * FROM topscoresNew ORDER BY Score DESC LIMIT 3";
$result = mysql_query($query);
$scoresArray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$scoresArray[$i]['Score'] = $row['Score'];
$scoresArray[$i]['Naam'] = $row['Naam'];
$i++;
}
echo json_encode($scoresArray);
}
check json:
if (isset($_POST['json'])) {
$score = json_decode($_POST['json'], true);
InsertScore($score);
} else {
GetScores();
}
Make the ajax-calls synchronous:
$.ajax({
type: "POST",
url: "Database.php",
dataType: "json",
data: { json: jsonData },
async: false
});
This way the 'select'-call will wait for the 'insert'-call to finish.

Categories