How to properly set POST value from AJAX? - php

I want to pass the value from jquery to php using AJAX, the problem is the value in the php is not properly set.
Here is my sample codes:
Button trigger to pass data into jquery.
<button class="btn btn-info add-percentage"
data-landing_id-percentage="'.$row['hidden_id'] .'"
data-toggle="add-percentage"><i class="glyphicon glyphicon-time"></i></button>
Below is the ajax and jquery code.
<script>
$(".add-percentage").click(function(){
var landing_id = $(this).data('landing_id-percentage');
$.ajax({
url: 'ajax/readPercentage.php',
type: 'POST',
data: {
landing_id: landing_id
},
success: function(msg) {
alert('Email Sent'+msg);
$('#add-percentage').modal('show');
readRecords();
}
});
});
<script>
The result below in the php code is the landing_id is not properly set.
readPercentage.php
<?php
$data = '
<table class="table table-bordered table-hover table-striped" id="ModalMyTable">
<thead>
<tr class="success">
<th ><center>No.</center></th>
<th ><center>Percentage ID</center></th>
<th ><center>Landing ID</center></th>
<th><center>Percentage</center></th>
<th><center>Date Added</center></th>
</tr>
</thead>';
if(isset($_POST['landing_id'])){
$landing_id = $_POST['landing_id'];
$query = mysqli_query($conn, "SELECT
percentage.percent_id,
percentage.landing_id,
percentage.percentage,
percentage.date_recorded
FROM
percentage
WHERE percentage.landing_id = '$landing_id'");
$number = 1;
while($row = mysqli_fetch_assoc($query)) {
$data .= '
<tr>
<td><center>' . $number . '</center></td>
<td><center>' . $row['percent_id'] . '</center></td>
<td><center>' . $row['landing_id'] . '</center></td>
<td><center>' . $row['percentage'] . '%</center></td>
<td><center>' . date("M. d, Y", strtotime($row['date_recorded'])) . '</center></td>
</tr>';
$number++;
}
}else{
$data .='<tr><td colspan="6">Landing id is not properly set!</td></tr>';
}
$data .= '</table>
<script>
{
$(document).ready(function(){
$("#ModalMyTable").DataTable();
readRecords();
});
}
</script>
';
echo $data;
?>
I hope some one can help me in my problem. Thanks in advance.

Related

Problems passing Ajax result to table Codeigniter

I'm trying to get table data to my view table using Codeigniter and AJAX jQuery.
Well, I'm using a document ready function to get the data instead of passing the table data when calling the view on the controller.
Ajax function
$( document ).ready(function() {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
alert("sucesso - " + data);
$('#example1').html(data);
},
error: function() {
alert('Algo falhou, nao caregou a tabela. - ' + data);
}
});
});
Controller method
public function crud_getDataAll($table_name)
{
$data = $this->Administracao_model->getAllData($table_name);
echo json_encode($data);
}
Model method
function getAllData($table_name)
{
$this->db->select('*');
$query = $this->db->get($table_name);
return $query->result();
}
View table
<table id="example1" class="table table-sm table-bordered table-striped Responsive">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Nome</th>
<th class="text-center">Ações Permissíveis</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if($data){ foreach($data as $row) { ?>
<tr>
<td class="align-middle text-center">
<?php echo $row->id;?>
</td>
<td class="align-middle text-center">
<span class="badge <?php echo $row->classes; ?>">
<?php echo $row->none;?>
</span>
</td>
<?php $ad = $row->adicionar; $el = $row->eliminar; $al = $row->alterar; $pe = $row->pesquisar; ?>
<td>
<?php echo $ad .", ". $el . ", ". $al . ", " . $pe; ?>
</td>
</tr>
<?php } } ?>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Amostra</th>
<th>Ações Permissíveis</th>
<th>Ação</th>
</tr>
</tfoot>
</table>
Is there something that I'm doing wrong? Thanks in advance.
Php error:
Severity: Notice
Message: Undefined variable: data
EDITED
output of echo json_encode($data);
[
{
"id": "1",
"nome": "Nivel 0",
"classe": "badge-admin-0",
"adicionar": "1",
"remover": "1",
"alterar": "1",
"pesquisar": "1"
},
{
"id": "2",
"nome": "Teste",
"classe": "badge-danger",
"adicionar": "1",
"remover": "0",
"alterar": "0",
"pesquisar": "0"
}
]
Basically you have 2 options here. First of all, if you're not passing $data to your HTML table, then remove PHP codes:
<table id="example1" class="table table-sm table-bordered table-striped table-responsive">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Nome</th>
<th class="text-center">Ações Permissíveis</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Amostra</th>
<th>Ações Permissíveis</th>
<th>Ação</th>
</tr>
</tfoot>
</table>
but if you're passing the data, leave as it is.
Option 1: Output data as HTML
$( document ).ready(function() {
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
processData: false,
dataType: 'html',
success: function(data) {
$('#example1 tbody').html(data);
},
error: function(xhr) {
alert('Algo falhou, nao caregou a tabela. - ' + xhr.statusText);
}
});
});
Then, in your controller, output data as HTML:
public function crud_getDataAll($table_name)
{
$rows = $this->Administracao_model->getAllData($table_name);
foreach($rows as $row) {
echo '<tr>';
echo '<td class="align-middle text-center">' . $row->id . '</td>';
echo '<td class="align-middle text-center"><span class="badge ' . $row->classe . '">' . $row->nome . '</span></td>';
echo '<td>' . $row->adicionar . ', ' . $row->eliminar . ', ' . $row->alterar . ', ' . $row->pesquisar . '</td>';
echo '</tr>';
}
}
Option 2: Output data as JSON
Just update your AJAX callback:
$( document ).ready(function() {
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
processData: false,
dataType: 'json',
success: function(rows) {
if (rows) {
rows.forEach(function(row) {
$('#example1 tbody').append(`<tr><td class="align-middle text-center">${row.id}</td><td class="align-middle text-center"><span class="badge ${row.classe}">${row.nome}</td><td>${row.adicionar}, ${row.eliminar}, ${row.alterar}, ${row.pesquisar}</td></tr>`);
});
}
},
error: function(xhr) {
alert('Algo falhou, nao caregou a tabela. - ' + xhr.statusText);
}
});
});

Table functions doesn't work when using ajax

So I've been using php for a while now but recently, I've decided to use ajax so I can view live data and I don't have to refresh the page to see changes in the database. And I created a page and the fetch function works but when it's in the table, the table functions doesn't work. At the bottom of the table it says it's showing 0 out of 0 entries and the sort by function and the show {limit} function doesn't work either. It's like somehow the table div doesn't read the data inside.
Here's my code:
<div class="body" >
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover js-basic-example dataTable" >
<thead>
<tr>
<th width="155">Action</th>
<th width="90">LRN</th>
<th width="45">Level</th>
<th>Name</th>
<th width="15">Gender</th>
<th width="65">Type</th>
<th width="110" style="font-size: 14px!important;">Date Enrolled</th>
<th width="40">Card</th>
</tr>
</thead>
<tbody id="live-data">
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready( function() {
function fetch_data() {
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
console.log(data);
$('#live-data').html(data);
}
});
}
fetch_data();
});
</script>
Here's fetch.php
<?php
include('../global/db.php');
$output = '';
$query ="SELECT * FROM students WHERE status = '0' ORDER BY date_enrolled DESC";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
$date_enrolled = $row['date_enrolled'];
$card = $row['card'];
$stud_birth = $row['stud_birth'];
$age = date('Y', strtotime($stud_birth)); $year = date('Y '); $age = (int)$age; $year = (int)$year;
$sage = $year - $age;
$output .= '
<tr>
<td>
<button type="button" class="btn bg-cyan btn-xs waves-effect" data-toggle="modal" data-target="#'.$row['stud_id'].'">
<i class="material-icons">search</i>
<span>Profile</span>
</button> <button type="button" class="btn bg-orange btn-xs waves-effect" data-toggle="modal" data-target="#'.$row['stud_id'].''.$row['stud_id'].'">
<i class="material-icons">search</i>
<span>Approve</span>
</button>
</td>
<td>'.$row['stud_lrn'].'</td>
<td>'.$row['stud_grade'].'</td>
<td>'.$row['stud_lname'].', '.$row['stud_fname'].' '.$row['stud_mname'].'</td>
<td>'.$row['stud_gender'].'</td>
<td>'.$row['stud_type'].'</td>
<td style="font-size: 12px!important;">'.$date_enrolled = date("M-d-Y g:i A", strtotime($date_enrolled)).'</td>
<td>';
if ($card == "") {
$output .= '
<center>N/A</center>';
}
else {
$output .= '
<center><a target="_blank" href="../image-gallery/20.jpg" data-sub-html="Demo Description">
<img class="img-responsive" src="../image-gallery/thumb/thumb-20.jpg" style="width: 70px; height: 35px;"></a></center>';
}
$output .= '
</td>
</tr>';
}
}
else {
$output .= '
<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
echo $output;
?>
I think you are using dataTable jquery library . Problem is its not right way to use datatabe . you need a json format out from backend like as
{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011/07/25",
"$170,750"
],
}
Don't forget to warp with {data:[]} object
after then simply use in ajax
$(document).ready(function() {
$('#live-data').DataTable( {
"ajax": 'fetch.php'
} );
} );
For more ...
https://datatables.net/examples/data_sources/ajax.html

Search by date range and by keyword

For report generation in the project I made I want to use 2 methods:
By date range (from date and up to date)
By employee ID
While using the above keywords the complete record of the employee should be displayed in that particular range.
For ex- emp1234 is the employee whose record is to be checked between date 20 may 2018 to 30 june 2018. The result must be displayed in between the range
Another thing is that the search can be done either by date or by employee id or both but both should not be compulsory.
the script is as follows:
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#report_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#report_table').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
I need to combine these two different queries into one.
filter.php
<?php
//filter.php
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost", "root", "", "ais");
$output = '';
$query = "
SELECT * FROM tbl_employees,tbl_in_time_attendance,tbl_out_time_attendance WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date AND tbl_in_time_attendance.date AND tbl_out_time_attendance.date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'
";
$result = mysqli_query($connect, $query);
$cnt=1;
$output .= '
<table class="table table-bordered">
<tr>
<th width="6%">Sr No.</th>
<th width="15%">EMPLOYEE ID</th>
<th width="20%">EMPLOYEE NAME</th>
<th width="15%">IN_TIME</th>
<th width="15%">OUT_TIME</th>
<th width="15%">DATE</th>
<th width="25%">WORKING HOURS</th>
</tr>
';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$outtime = $row["outtime"];
$intime = $row["intime"];
$array1 = explode(':', $intime);
$array2 = explode(':', $outtime);
$minutes1 = ($array1[0] * 60.0 + $array1[1])/60;
$minutes2 = ($array2[0] * 60.0 + $array2[1])/60;
$diff = round(($minutes2 - $minutes1),1).' hrs';
$output .= '
<tr>
<td align="center">'. $cnt .'</td>
<td align="center">'. $row["EmpId"] .'</td>
<td align="center">'. $row["FirstName"] . " " . $row["LastName"].'</td>
<td align="center">'. $row["intime"] .'</td>
<td align="center"> '. $row["outtime"] .'</td>
<td align="center">'. $row["date"] .'</td> ';
if ($diff < 8) {
$output .= '<td align="center" style="background-color: #F42E2E;"> ' . $diff . ' </td>';
} else {
$output .= '<td align="center" style="background-color: #55E443;"> ' . $diff . ' </td>';
}
$output .= '</tr>';
$cnt++;
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Record Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
Fetch.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ais");
$output = '';
if(isset($_POST["query"]))
{
$query = "
SELECT * FROM tbl_employees,tbl_in_time_attendance,tbl_out_time_attendance WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date AND tbl_in_time_attendance.date AND tbl_employees.EmpId LIKE '".$_POST["query"]."' ";
}
else
{
$query = "SELECT * from tbl_employees, tbl_in_time_attendance , tbl_out_time_attendance WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$cnt=1;
$output .= '
<table class="table table-bordered">
<tr>
<th width="6%">Sr No.</th>
<th width="15%">EMPLOYEE ID</th>
<th width="20%">EMPLOYEE NAME</th>
<th width="15%">IN_TIME</th>
<th width="15%">OUT_TIME</th>
<th width="15%">DATE</th>
<th width="25%">WORKING HOURS</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$outtime = $row["outtime"];
$intime = $row["intime"];
$array1 = explode(':', $intime);
$array2 = explode(':', $outtime);
$minutes1 = ($array1[0] * 60.0 + $array1[1])/60;
$minutes2 = ($array2[0] * 60.0 + $array2[1])/60;
$diff = round(($minutes2 - $minutes1),1).' hrs';
$output .= '
<tr>
<td align="center">'. $cnt .'</td>
<td align="center">'. $row["EmpId"] .'</td>
<td align="center">'. $row["FirstName"] . " " . $row["LastName"].'</td>
<td align="center">'. $row["intime"] .'</td>
<td align="center"> '. $row["outtime"] .'</td>
<td align="center">'. $row["date"] .'</td> ';
if ($diff < 8) {
$output .= '<td align="center" style="background-color: #F42E2E;"> ' . $diff . ' </td>';
} else {
$output .= '<td align="center" style="background-color: #55E443;"> ' . $diff . ' </td>';
}
$output .= '</tr>';
$cnt++;
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Record Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
?>
I want these to separate fetch and filter files into one file.
Please help.
please dont delete the question again, i was writing a few minutes and then the question was deleted haha
soo, as you have a filter button which has to be clicked to get the results there are two ways you can choose!
you display your table with datatable plugin which means you only need to filter by date and then write the employeeid in the searchbox and you will only see the results for this person WITHOUT having to query it again!
https://datatables.net/
you get the two dates AND your search query by clicking on the filter button which means you will only have one php file (i dont know why you actually want to use fetch & filter).. In your php file you then look if there are only dates submitted OR the query is also submitted:
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
var query = $("#search_text").val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date, to_date:to_date, employee: query},
success:function(data)
{
$('#report_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
in php file
if(isset($_POST["employee"]) AND $_POST["employee"] != "") {
// make your sql call with dates AND employeeid
} else {
// make your sql call only with dates
}
depending on how many results you have I'm sure its also possible to dont even have to query again for different dates and instead tweak datatable so that you have one from_date, one to_date and one search field and filter the table after keyup.. see example here: https://datatables.net/examples/api/multi_filter.html

Append Data To Tbody AJAX

I have a foreach statement that is adding the data from a DB to my table rows
HTML
<table id="myTable" class="display table center-table" width="100%" >
<thead>
<tr>
<th>Product #</th>
<th>Alternate #</th>
<th>Description</th>
<th>On Hand</th>
<th>Condition</th>
</tr>
</thead>
<tbody id="productResults"> </tbody>
</table>
PHP
$query = $sql . " limit " . $start . "," . $perPage;
$data = $db_handle->runQuery($query);
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = $db_handle->numRows($sql);
}
$pages = ceil($_GET["rowcount"]/$perPage);
$output = '';
if(!empty($data)) {
$formval = '<input type="hidden" class="pagenum" value="' . $page . '" /><input type="hidden" class="total-page" value="' . $pages . '" />';
foreach($data as $k=>$v) {
$output .= '<tr><td>' . $formval . $data[$k]["wuno_product"] . '</td>';
$formval = '';
$output .= '<td>' . $data[$k]["wuno_alternates"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_description"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_onhand"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_condition"] . '</td></tr>';
}
}
echo $output;
Then in my user view I am adding the data back to the page like this,
JQUERY
<script>
(function($) {
$(document).ready(function(){
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: { rowcount:$("#rowcount").val() },
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){/* convert to dom element */
$("#productResults").append( data.toElement() );
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
if($(".pagenum:last").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum:last").val()) + 1;
getresult('<?php echo $assetPath; ?>?page='+pagenum);
}
}
});
});
})( jQuery );
</script>
But when it shows up in my page it shows up outside of the table and does not have the html added to it. It looks like this in the page,
8855K5MS21026-B2111212M39029/5-1171313Q4559PROD CODE: 4057911RESTOCKING CHARGE11TAS8732-1C277TEST REPORTS6690H549(W) LAMP CKT99MEC-1MF1 FEET DB9M/F CABLE11T1-GMIL-L-25567E1 GAL JUG2121WL-322914VOLT T-1 BULB100100
Which was the data from the DB just all together... Why would this happen and how can I fix it?
It shows up above the table instead.
firstly, you are attempting to add to a table, but the first portion of your generated code is a form element outside the table structure; any modern browser is going to spot the mistake and add in the assumed missing
</table>
which is why the response is outside a table view.

Modifying the AJAX PHP database example

I would like to create something like this show here:
http://www.w3schools.com/PHP/php_ajax_database.asp
But instead of drop down list shown in the example, is it possible to change it to table format like example, when I click on the Class 1 it will display the details for class 1...the details are in my database its from phpmyadmin:
Thanks in advance...help greatly appreciated
Is this correct?
<?php
include ('staffheader.php');
?>
<div id="head">Permit Structure</div>
<div class="contents">
<div id="class_data">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td>Road Based</td>
<td>Proving Ground PG</td>
<td>Off Road OR</td>
<td>Towing TT</td>
</tr>
<tr id="Class_1">
<td> <a href='#' class='classlink' title='1'>Class 1</a></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Class 2</td>
<td>CAT 2PG</td>
<td>CAT 1OR</td>
<td>CAT 2TT</td>
</tr>
<tr>
<td>Class 3</td>
<td>CAT 3PG</td>
<td>CAT 2OR</td>
<td>CAT 3TT</td>
</tr>
<tr>
<td> </td>
<td>CAT 4PG</td>
<td>CAT 3OR</td>
<td> </td>
</tr>
</table>
</div>
<div id="instruction">Click on the Class or Category to view information on it</div>
</div>
<div id='detailtable'></div>
<?php
include('allfooter.php');
?>
loadergetclassinfo.php:
<?php
$class_id = empty($_POST["class_id"]) ? 1 : $_POST["class_id"];
$con = mysql_connect("localhost", "root", "cailing8195") or die ("Unable to connect to MySQL Server " . mysql_error());
if(is_resource($con))
$db = mysql_select_db("jlr", $con) or die( "Unable to select database " . mysql_error());
$query = "SELECT PTYPE, TYPE, PREREQ, DES FROM type WHERE TYID=" . $class_id;
$res = mysql_query($query);
$arr_data = mysql_fetch_assoc($res);
mysql_close($con);
foreach ($arr_data as $data)
$html = "<table>\n";
$html .= "<tr><th>Type ID</th><th>Permit Type</th><th>Categories</th><th>Pre-Requisisite</th><th>Description</th></tr>\n";
$html .= "<tr><td>" . $class_id . "</td><td>" . $data['PTYPE'] . "</td><td>" . $data['TYPE'] . "</td><td>" . $data['PREREQ'] . "</td><td>" . $data['DES'] . "</td> </tr>\n";
$html .= "</table>\n";
echo $html;
?>
JQuery (in javascript.js):
$(function() {
$('a.class_link').click(function() {
var class_id = $(this).attr('title');
$.post("loadergetclassinfo.php", {class: class_id}, function(result){
$('#detail_table').html(result);
});
});
});
And i add this inside my header php file too:
<script src="javascript.js"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
If you want the row in which you click the link, to be populated with the data from the database, do something like this (untested, but here is the gist):
HTML:
<tr id='class_1'>
<td><a href='#' class='classlink' title='1'>Class 1</a></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
jQuery:
$(function() {
$('a.classlink').click(function() {
var class_id = $(this).attr('title');
$.post("loadergetclassinfo.php", {class_id: class_id}, function(result){
$('#class_' + class_id).html(result);
});
});
});
loadergetclassinfo.php:
<?php
$class_id = empty($_POST["class_id"]) ? 1 : $_POST["class_id"];
$con = mysql_connect("localhost", "your_MySQL_username", "your_MySQL_password") or die ("Unable to connect to MySQL Server " . mysql_error());
if(is_resource($con))
$db = mysql_select_db("your_MySQL_database", $con) or die( "Unable to select database " . mysql_error());
$query = "SELECT data1, data2, data3 FROM your_data_table WHERE class=" . $class_id;
$res = mysql_query($query);
$arr_data = mysql_fetch_assoc($res);
mysql_close($con);
$html = "<td><a href='#' class='classlink' title='$class_id'>Class $class_id</a></td>";
foreach ($arr_data as $data)
$html .= "<td>" . $data . "</td>\n";
echo $html;
?>
UPDATE:
If you want the 'Class x' data to appear somewhere else in your HTML page, you can maybe do something like this:
Add this to your HTML:
<div id='class_data'></div>
Change above jQuery like this:
$.post("loadergetclassinfo.php", {class: class_id}, function(result){
$('#class_data').html(result);
});
Change above php code to something like this (or you can use a list or whatever you like to see here):
$html = "<table>\n";
$html .= "<tr><th>Class Number</th><th>Data 1</th><th>Data 2</th><th>Data 3</th></tr>\n";
$html .= "<tr><td>" . $class_id . "</td><td>" . $data['data1'] . "</td><td>" . $data['data2'] . "</td><td>" . $data['data3'] . "</td></tr>\n";
$html .= "</table>\n";
echo $html;
This is assuming that you have columns called data1 etc and that your primary index is called 'class'. Just change it to what it is in your case.
UPDATE in RESPONSE TO YOUR EDITS:
End your HTML code with:
<div id='detailtable'></div>
Edit this jQuery statement:
$.post("loadergetclassinfo.php", {class: class_id}, function(result){
$('#detailtable').html(result);
});
Finally, remove the php code from below your HTML table, and put it in it's own file called "loadergetclassinfo.php" in the same directory as the HTML file.
ALSO, this is wrong (sorry, error was in my code):
$class_id = empty($_POST["class_id"]) ? 1 : $_POST["class"];
Should be:
$class_id = empty($_POST["class_id"]) ? 1 : $_POST["class_id"];
Also change the details table code to:
$html = "<table>\n";
$html .= "<tr><th>Type ID</th><th>Permit Type</th><th>Categories</th><th>Pre- Requisisite</th><th>Description</th></tr>\n";
$html .= "<tr><td>" . $class_id . "</td><td>" . $data['PTYPE'] . "</td><td>" . $data['TYPE'] . "</td><td>" . $data['PREREQ'] . "</td><td>" . $data['DES'] . "</td></tr>\n";
$html .= "</table>\n";
you can try to use ajax function from jquery it could be somethink like this again you could modify it.
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td>Road Based</td>
<td>Proving Ground PG</td>
<td>Off Road OR</td>
<td>Towing TT</td>
</tr>
<tr>
<td onclick="getPage(this)" >Class 1</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<div id='content'></div>
<script type="text/javascript">
function getPage(class) {
//generate the parameter for the php script
var data = 'page=' + document.location.hash.replace(/^.*#/, '');
$.ajax({
url: "loadergetclassinfo.php",
type: "GET",
data: (class).innerText,
cache: false,
success: function (html) {
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
</script>

Categories