Assistance with dataTables not processing my table - Laravel & Ajax - php

I am trying to get dataTables to process my table in Laravel using an ajax script, I have no pages of search function.
'datatables.min.js' pulls through in chrome dev sources from CDN and I know my ajax is working because other scripts work fine on the page.
I am using some basic custom CSS on the table via a custom.css file, but I was under the impression that is fine.
My controller code.
// FETCH ALL AJAX REQUEST
public function fetchAll()
{
$vehicles = Vehicle::all(); //Could be model or controller...
$output = '';
if ($vehicles->count() > 0) {
$output .= '<table #"showAll" class="veh-table table table-striped table-sm text-center align-middle" >
<thead>
<tr>
<th class="tbl-head">ID</th>
<th class="tbl-head">Image</th>
<th class="tbl-head">Make</th>
<th class="tbl-head">Model</th>
<th class="tbl-head">Derivative</th>
<th class="tbl-head">Powertrain</th>
<th class="tbl-head">Transmission</th>
<th class="tbl-head">Fuel Type</th>
<th class="tbl-head">Model Year</th>
<th class="tbl-head"><i class="bi-gear-fill h5"></i></th>
</tr>
</thead>
<tbody>';
foreach ($vehicles as $vehicle) {
$output .= '<tr class="tbl exp_tbl">
<td>'.$vehicle->id.'</td>
<td><img src="./storage/images/'.$vehicle->image.'" class="img-thumbnail justify-content-sm-center"></td>
<td>'.$vehicle->make.'</td>
<td>'.$vehicle->model_name.'</td>
<td>'.$vehicle->version.'</td>
<td>'.$vehicle->powertrain.'</td>
<td>'.$vehicle->trans.'</td>
<td>'.$vehicle->fuel.'</td>
<td>'.$vehicle->model_year.'</td>
<td>
<i class="bi-pencil-square h6"></i>
<i class="bi-trash h6"></i>
</td>
</tr>';
}
$output .= '</tbody></table>';
echo $output;
} else {
echo '<h1 class="text-center text-secondary my-5">No vehicles in the database!</h1>';
}
}
The function from my html.
...
$(function() {
...
// SHOW ALL VEHICLES AJAX REQUEST
fetchAllVehicles();
function fetchAllVehicles(){
$.ajax({
url: '{{route('fetchAll')}}',
method: 'GET',
success: function(res){
$("#show_all_vehicles").html(res);
$("#showAll").DataTable({
order: [ 0, "desc" ]
});
}
});
}
...
}
...
I have tried adding
{
dataType: 'json',
processData: true, // & false...
serverSide: false, // & true...
}
Please let me know if I haven't included some needed information.

Try to change
$output .= '<table #"showAll"....
to
$output .= '<table id="showAll"....
and let me know if that works

Related

Fetch data using AJAX and Codeigniter?

I am trying to fetch data into a table and nothing happens.
No table appears
No data is fetched
Controller
public function indexajax()
{
if($this->input->post("action")=='FetchAllUserUingAjax')
{
$this->load->model("usersmodel");
$data["allu"]=$this->usersmodel->ShowAllUsers("users");
$data['pagetitle']=" -->All Users Using Ajax<--";
foreach ($allu as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
</tr>';
endforeach;
$this->load->view("template/admin/header",$data);
$this->load->view("users/allusersusingajax",$data);
$this->load->view("template/admin/footer");
}
}
jQuery
<script>
$(document).ready(function () {
FetchAllUserUingAjax();
function FetchAllUserUingAjax() {
$.ajax({
url:'<?php echo base_url()?>Users/indexajax',
method:"post",
success:function (data) {
$(".userdataajax table").append(data);
}
})
var action="FetchAllUserUingAjax";
$.ajax({
url:"<?php echo base_url()?>Users/indexajax",
method:"post",
data:{action:action},
success:function (data) {
$(".userdataajax table tr ").not("table tr:first").remove();
$(".userdataajax table").append(data);
Table();
}
})
}
})
</script>
Model
public function ShowAllUsers()
{
$sql=$this->db->get("users");
return $sql->result();
}
View
<div class="userdataajax table-responsive">
<table class=" table table-responsive table-bordered">
<tr>
<th>#</th>
<th>name</th>
<th>image</th>
<th> full name</th>
<th>email</th>
<th>usertype</th>
<th>status</th>
<th>reg date</th>
<th>reg time</th>
<th>delete</th>
<th>edit</th>
<th>Activate</th>
<th>disactivate</th>
</tr>
</table>
</div>
Your code hints at other relevant code that is not shown. I'm taking what you show as all that needs to be known. Here's what I see based on that premise.
First, the view. Add an id to the table. It makes JQuery selectors so much easier. The JavaScript is in this file which is "users/allusersusingajax.php".
<div class="userdataajax table-responsive">
<table id='user-table' class=" table table-responsive table-bordered">
<tr>
<th>#</th>
<th>name</th>
<th>image</th>
<th> full name</th>
<th>email</th>
<th>usertype</th>
<th>status</th>
<th>reg date</th>
<th>reg time</th>
<th>delete</th>
<th>edit</th>
<th>Activate</th>
<th>disactivate</th>
</tr>
</table>
</div>
<script>
$(document).ready(function () {
function FetchAllViaAjax() {
$.ajax({
url: '<?= base_url("users/get_all_users") ?>',
method: "post",
dataType: 'html',
success: function (data) {
var table = $("#user-table");
table.not("table tr:first").remove();//your code makes it unclear why you need this
table.append(data);
}
});
FetchAllViaAjax();
}
});
</script>
The controller needs two methods. One to show the table another to get the rows. This is the file Users.php
//show the page which includes the basic <table> and header row
public function indexajax()
{
// The code and question text give no reason for this conditional test
// So I'm removing it
//if($this->input->post("action") == 'FetchAllUserUingAjax')
//{
$data['pagetitle'] = "-->All Users Using Ajax<--";
$this->load->view("template/admin/header", $data);
$this->load->view("users/allusersusingajax");
$this->load->view("template/admin/footer");
//}
}
//respond to ajax request
public function get_all_users()
{
$this->load->model("usersmodel");
$allu = $this->usersmodel->ShowAllUsers("users");
$out = ''; //if the model returned an empty array we still have a string to echo
//using PHP's output buffer to simplify creating a big string of html
ob_start(); //start output buffering
foreach($allu as $a):
?>
<tr><td><?= $a->id; ?></td><td><?= $a->username; ?></td></tr>
<?php
endforeach;
$out .= ob_get_clean(); //append the output buffer to the $out string
echo $out;
}
Read about PHP's Output Control Functions
I'd first update my model to return an array:
return $sql->result_array();
Then in your controller, you don't need to load a view:
public function indexajax()
{
if($this->input->post("action")=='FetchAllUserUingAjax')
{
//set content type
header("Content-type: application/json");
$this->load->model("usersmodel");
echo json_encode(
$this->usersmodel->ShowAllUsers(); //this method doesn't expect an argument, no need to pass one
);
}
}
Then in your ajax callback:
success: function(resp){
$.each(resp, function(k,v){
console.log(v);
});
}

Ajax / Php sending id from while loop on click to view record details

i have a table with differente IDs on each row (obtained from a while loop), and next to each ID i have element to view the details of this specific record. Now i understand if i want to retrieve the id, i have to send via post method in a form, but i don't want the page to refresh because i'm using bootstrap tabs, i don't want the page to go back to the first tab, therefore, i'm trying to use Ajax not to make the page refresh.
So first of all i have my first table :
I am in Medical Records Tab > Member Medical Records.
and my View item is :
<td style='text-align:center;'> <ul class='nav nav-tabs'><form><a data-toggle='tab' id='testz' value='".$rowmed[0]."' href='#viewMed' role='button'></form><i style='color: gray;' class='fa fa-eye'></i></a></td></ul>
Now i write an ajax script with the variable recdetailsid in DATA:
<script>
$("#testz").click(function(e) {
switchVisible();
e.preventDefault();
$(this).toggleClass( "selected" );
$.ajax({
type: "POST",
data: {
recdetailsid: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Viewing Details !');
},
error: function(result) {
alert('error');
}
});
});
`
and then to get this ajax element :
if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
if(isset($_POST['recdetailsid'])){
$recdetailsid=$_POST['recdetailsid'];
$sqlmedr = "Select Record_id,Medical_Condition,Date,Notes FROM medicalrecords,teachers WHERE Teacher_id=".$comid." and medicalrecords.CommonID=teachers.CommonID and Dependant_id IS NULL and Record_id=".$recdetailsid." ";
// Created 2 same queries with different names because can't fetch_array twice on the same query and need to pull data twice, 1 outside the while and 1 in a while for table results
$sqlmedrx = "Select Record_id,Medical_Condition,Date,Notes FROM medicalrecords,teachers WHERE Teacher_id=".$comid." and medicalrecords.CommonID=teachers.CommonID and Dependant_id IS NULL and Record_id=".$recdetailsid." ";
// Record_id need to be sent on view click !!!!!!!!!!!! now it is specified explicitely
$resultmedr = $conn->query($sqlmedr);
$resultmedrx = $conn->query($sqlmedrx);
?>
<div class="jumbotron" style="margin-top: 20px; padding-left:0px !important;">
<h3 style="color:black;">Member Record</h3></div>
<?php
$rowmedrx = mysqli_fetch_array($resultmedrx);
if ($type=='teachers') {
echo "Record Id: <td>".$rowmedrx['Record_id']."</td> ";
echo "<table class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th>Condition</th>
<th>Date Of Diagnosis</th>
</tr>
</thead>";
while ($rowmedr = mysqli_fetch_array($resultmedr)) {
echo "<tr>
<td>".$rowmedr['Medical_Condition']."</td>
<td>".$rowmedr['Date']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
echo "Notes : <td>".$rowmedrx['Notes']."</td> ";
} else {
$sqlmedr = "Select DISTINCT Record_id,Medical_Condition,Date FROM medicalrecords,teachers,dependants WHERE medicalrecords.Dependant_id=".$comid." and medicalrecords.Dependant_id=dependants.Dependant_id ";
$resultmedr = $conn->query($sqlmedr);
echo "<table class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th>Condition</th>
<th>Date Of Diagnosis</th>
</tr>
</thead>";
while ($rowmedr = mysqli_fetch_array($resultmedr)) {
echo "<tr>
<td>".$rowmedr['Medical_Condition']."</td>
<td>".$rowmedr['Date']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
}
} }
?>
<div class="jumbotron" style="margin-top: 20px; padding-left:0px !important; ">
<h3 style="color:black;">Documents</h3></div>
But everything in the server $_POST brackets and isset $_POST brackets does not show, only the alert shows with the Document jumbotron.
( you can see i'm using the variable inside the query, Record_id=".$recdetailsid." ) , this is my whole purpose !
Can anyone give me some tips or help please ? i'm new to ajax but trying my best to get through this, appreciated!

isset and !empty for ajax posted variable retrieval php

I have a button group consisting of two buttons, each assigned an id and a value :
echo "<div style='margin-top:20px;' class='btn-group'>
<button type='button' class='btn btn-primary' id='btnconventional' value='conventional' style=' border-radius: 3px;'>Conventional Units</button>
<button type='button' class='btn btn-primary' id='btnsi' value='si' style=' border-radius: 3px;'>SI Units</button>
</div>";
And then i want to submit a query and table result depending on the value of the button that will be sent via this ajax script :
<script>
$("#btnconventional").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
Metric: $('#btnconventional').val(), // < note use of 'this' here
},
success: function(result) {
alert('Viewing conventional units');
},
error: function(result) {
alert('error');
}
});
});
</script>
Now when i try to get the variable and run my code, nothing appears but the else statement:
if(isset($_POST['Metric']) && !empty($_POST['Metric'])){
$sql2 = "Select DISTINCT Record_id,Test_Group,Test_Name,Result,subtests.Units from tests,medicalrecords,subtests WHERE medicalrecords.CommonID=".$comid." and medicalrecords.Subtest_id IS NOT NULL AND medicalrecords.Subtest_id=subtests.Subtest_id AND subtests.Test_id=tests.Test_id and tests.Test_Group='CBC'";
$result2 = $conn->query($sql2);
echo $_POST['Metric'];
echo "<table style='margin-top:10px;' class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th style='text-align:center;'>CBC</th>
<th style='text-align:center;'>Result</th>
</tr>
</thead>";
while ($row2 = mysqli_fetch_array($result2)) {
echo "<tr>
<td style='text-align:center;'>".$row2['Test_Name']."</td>
<td style='text-align:center;'>".$row2['Result']." ".$row2['Units']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
echo "<button onclick='hideLabResult();'>Back</button>";
}
else echo "Nope";
The success alert is showing after clicking the button, yet "Nope" still shows after the click, it's not going into the if statement and I can't seem to find out way, I'm a starter in ajax and I'd appreciate any tip or help please.
So in success you are only registered to display information about a successful request, not its contents. To display its contents, use $('.btn-group').html(result); for jquery example.
well, when I run the code on my local , I found ajax was not sending the request to correct page. When I put url then success message was showing there with all html code(whole page I mean). Then I write isset condition on top of page and at ending of } i put exit().
Now its working.
<?php
if(isset($_POST['Metric']) && !empty($_POST['Metric']))
{
$sql2 = "Select DISTINCT Record_id,Test_Group,Test_Name,Result,subtests.Units from tests,medicalrecords,subtests WHERE medicalrecords.CommonID=".$comid." and medicalrecords.Subtest_id IS NOT NULL AND medicalrecords.Subtest_id=subtests.Subtest_id AND subtests.Test_id=tests.Test_id and tests.Test_Group='CBC' ";
$result2 = $conn->query($sql2);
$html = $_POST['Metric'];
$html.= "<table style='margin-top:10px;' class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th style='text-align:center;'>CBC</th>
<th style='text-align:center;'>Result</th>
</tr>
</thead>";
while ($row2 = mysqli_fetch_array($result2)) {
$html.= "<tr>
<td style='text-align:center;'>".$row2['Test_Name']."</td>
<td style='text-align:center;'>".$row2['Result']." ".$row2['Units']."</td>
</tr>";
}
$html .="<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
$html .= "<button onclick='hideLabResult();'>Back</button>";
echo $html;
} else echo "Nope"; ?>
<script>
$("#btnconventional").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
Metric: $('#btnconventional').val(), // < note use of 'this' here
},
url : '', // put your page url
success: function(result) {
alert('Viewing conventional units'+result);
},
error: function(result) {
alert('error');
}
});
});
</script>

PHP - If database record is a specific value, only show these buttons

I have a multi-step form that allows the user to save for later or submit. If they save for later, i want them to have an option to edit or delete but if they submit, i dont want them to have any option to edit or delete. Although the following code makes sense, its not working; i'm not getting any buttons and it breaks the jquery table plugin and i dont have the search or pagination option:
<table id="myTable" class="table table-bordered table-hover table-striped tablesorter table-responsive">
<thead>
<tr>
<td>Id</td>
<td>Status</td>
<td>Date/Time</td>
<td>Tag</td>
<td>Serial Number</td>
<td>Equipment</td>
<td>Company</td>
<td>Grand Total</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['id']."</td>";
echo "<td><span class='label ".$res['labelwarning']."'>".$res['status']."</span></td>";
echo "<td>".$res['todaysdatetime']."</td>";
echo "<td>".$res['tag']."</td>";
echo "<td>".$res['serialnumber']."</td>";
echo "<td>".$res['currentequipment']."</td>";
echo "<td>".$res['company']."</td>";
echo "<td>".$res['total_grandtotal']."</td>";
$Submitted = "Submitted";
$Saved = "Saved";
if ($res['labelwarning'] == $Submitted) {
echo "<td></td>";
} elseif ($res['labelwarning'] == $Saved) {
echo "<td></td>";
}
echo "</tr>";
}
?>
<Script>
$(document).ready(function() {
$("#myTable").dataTable({
"aaSorting": [ [0,'desc'] ]
});
});
</Script>
Oke I will try to explain this process here:
1 - First you will create a php file where you will fetch the results you need.
when you are fetching the records you will put your results in a variable like so:
$result_html = '';
while($res = mysqli_fetch_array($result)) {
$result_html .= "<tr>";
$result_html .= "<td>".$res['id']."</td>";
...en so on
$result_html .= "</tr>";
}
To return the response to your ajax call you need to add also this:
echo json_encode($result_html);
2 - Before the end </body> tag
<script>
$(document).ready(function() {
$.ajax({
url: '/path/to/the_php_file',
type: 'POST',
dataType: 'json',
data : { //only needed if you have to pass parameters to your query },
})
.done(function(data) {
//data is your html response
// and #returnedResponse is the id given to your body tag
$('#returnedResponse').html(data);
$("#myTable").dataTable();
})
.fail(function() {
console.log("error");
});
});
</script>
3 - Your table
<table id="myTable" class="table table-bordered table-hover table-striped tablesorter table-responsive">
<thead>
<tr>
<td>Id</td>
<td>Status</td>
<td>Date/Time</td>
<td>Tag</td>
<td>Serial Number</td>
<td>Equipment</td>
<td>Company</td>
<td>Grand Total</td>
<td>Action</td>
</tr>
</thead>
<tbody id="returnedResponse">
</tbody>
</table>
NOTE:
You need to have the link to the jquery.js before your ajax call.
This is not a copy and paste solution. You asked for an example on how to do it and here you have a good start point to learn it.
Try to change your if/else part to this:
if ($res['labelwarning'] == $Submitted) {
echo "<td></td>";
} else{
echo "<td></td>";
}

Adding a loader to load a table with data jQuery or ajax

Here is the description of my issue:
I have a db connection here:
$host = 'some host credentials';
$dbh = 'My database';
Here is my statement:
$qry = "SELECT some_data FROM some_table LIMIT 1000";
$result = some code here;
Here is my while loop:
echo '<table class="table table-striped table-hover table-bordered" id="example">
<thead>
<tr class="test">
<th style="border: 1px solid #333;">PRODUCTPRICE</th>
<th>PRODUCTNAME</th>
<th>PRODUCTCODE</th>
<th>PRODUCTSALE</th>
<th>PRODUCTPRICE</th>
</tr>
</thead>
<tbody>';
while ($row = mysql_fetch_assoc($result)){
$PRODUCTID = intval($row["PRODUCTID"]);
$PRODUCTNAME = $row["PRODUCTNAME_1"];
$PRODUCTCODE = $row["PRODUCTCODE"];
$PRODUCTSALE = $row["PRODUCTSALE_"];
$PRODUCTPRICE = $row["PRODUCTPRICE"];
echo '<tr class="odd gradeX">
<td>'.$PRODUCTID.'</td>
<td>'.$PRODUCTNAME.'</td>
<td>'.$PRODUCTCODE.'</td>
<td class="center">'.$PRODUCTSALE.'</td>
<td class="center">'.$PRODUCTPRICE.'</td>
</tr>';
}
echo '</tbody>
</table></div>
</div>
</body>
</html>';
I want to make a loader before this content table display because there are more than 50,000 products. Something kind of processing or a circle showing that a content is loading, just a simple one, maybe jQuery or ajax. I have tried many tutorials till now but no success.
here is a scheme for that :
<div id="content"></div>
$.ajax({
url : 'the-above-script.php',
beforeSend : function() {
$("#content").html('<img src="ajax-icon-from-www.ajaxload.info">');
},
success : function(html) {
$("#content").html(html);
}
});

Categories