Extract data from a table created by a loop (PHP) - javascript

I have the following problem: I'm creating an HTML table with a PHP for-loop. There is data and a button in each row. When the user presses the button (id="detail"), the "id"-field of the corresponding row (id="patID") is supposed to be stored in a PHP variable. Every attempt I have made failed because javascript simply takes the first element on the page with the id "patID" and (to my knowledge) I don't have a way to select this element in PHP. This is my code:
<?php
if (isset($_POST['search']))
{
//irrelevant details of MySQL PDO-connection omitted
$result = $statement->fetchAll();
if ($result && $statement->rowCount() > 0)
{ ?>
<h2>Ergebnisse</h2>
<table>
<thead>
<tr>
<th>#</th>
<th>Vorname</th>
<th>Nachname</th>
<th>Geburtstag</th>
<th>Klasse/Kurs</th>
<th>Vorerkrankungen</th>
<th>Allergien</th>
<th>Anmerkung</th>
<th>Aktualisiert</th>
<th> Optionen</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result as $row)
{ ?>
<tr id="row">
<td id="patID"><?php echo escape($row["id"]); ?></td>
<td><?php echo escape($row["firstName"]); ?></td>
<td><?php echo escape($row["lastName"]); ?></td>
<td><?php echo escape($row["birthday"]); ?></td>
<td><?php echo escape($row["course"]); ?></td>
<td><?php echo escape($row["preIllnesses"]); ?></td>
<td><?php echo escape($row["allergies"]); ?> </td>
<td><?php echo escape($row["note"]); ?> </td>
<td><?php echo escape($row["created"]); ?> </td>
<td>
<button id="detail">Mehr</button>
</td>
</tr>
<? } ?>
</tbody>
</table>
<?php
}
else
{ ?>
<blockquote><b>Keine Ergebnisse gefunden.</b></blockquote>
<?php
}
}
?>

The 'id' attribute can only be given once to an html-element. You should you a class instead:
<button class="detail">Mehr</button>
You should store the id in an extra attribute if you want to grab it later in javascript. For example, if you are using jQuery, you can use a data attribute:
<button class="detail" data-id="some_id">Mehr</button>
<script>
$('.detail').click(function () {
var id = $(this).data('id');
// do something with id
});
</script>
This will add a click-listener to all elements with the 'detail' class. So if a user clicks on an element having that class , it will execute the given function with this pointing to the clicked element. And since that element has the 'data-id' attribute, we can use jQuery's data function to get the contents of that attribute.

Your way if you change ID to class
<tr class="row">
<td class="patID"><?php echo escape($row["id"]); ?></td>
<td><?php echo escape($row["firstName"]); ?></td>
<td><?php echo escape($row["lastName"]); ?></td>
<td><?php echo escape($row["birthday"]); ?></td>
<td><?php echo escape($row["course"]); ?></td>
<td><?php echo escape($row["preIllnesses"]); ?></td>
<td><?php echo escape($row["allergies"]); ?> </td>
<td><?php echo escape($row["note"]); ?> </td>
<td><?php echo escape($row["created"]); ?> </td>
<td>
<button class="detail">Mehr</button>
</td>
</tr>
<script>
$(function() {
$('.detail').click(function(){
// var id = $(this).parents('.row').find('.patID').html();
alert($(this).parents('.row').find('.patID').html());
});
});
</script>

Related

jquery or php if X is greater than Y

I'm making a website that displays a basic crud that shows Companyname, Stock, Minumum, Maximum.
I would like to display an alert or a message somewhere if the Stock is greater than the maximum. How could I go about doing this? Here is my display page code.
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Company Name</th>
<th>Stock</th>
<th>Minumum</th>
<th>Maximum</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['companyname']; ?></td>
<td><?php echo $row['stock']; ?></td>
<td><?php echo $row['minumum']; ?></td>
<td><?php echo $row['maximum']; ?></td>
<td><a class="btn btn-info" href="update1.php?id=<?php echo $row['id']; ?>">Edit</a> <a class="btn btn-danger" href="delete1.php?id=<?php echo $row['id']; ?>">Delete</a></td>
</tr>
You can put an additional message in the Stock column with an if statement.
<td><?php echo $row['stock']; ?></td>
with
<td><?php echo $row['stock']; if ($row['stock'] > $row['maximum']) { echo " > maximum"; } ?></td>

jquery how can I get data from html table row

I have the following table:
<table cellspacing="0" cellpadding="0" id="product">
<tr>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th colspan="2">Nr products</th>
</tr>
<?php foreach ($productsInStock as $product) : ?>
<tr>
<td><?php echo $product->getName(); ?></td>
<td><?php echo $product->getCategory(); ?></td>
<td><?php echo $product->getPrice().ProductController::coin; ?></td>
<td><?php echo $product->getNrProducts(); ?></td>
<td><button type="submit" value="Delete" class="upload" onclick="deleteDataTable();">Delete</button></td>
<input type="hidden" name="hiddenfieldname" class="hidden" value="<?php echo $product->getId();?>">
</tr>
<?php endforeach; ?>
</table>
I need the value for every hidden field but I only get the first :
x = ('.hidden').val() // gives the first value
How can I get the different values after every click on delete button
Simplest solution is pass the ID as parameter to deleteDataTable() function.
<td><button type="submit" value="Delete" class="upload" onclick="deleteDataTable(<?php echo $product->getId();?>);">Delete</button></td>
The problem is: Context.
When you use
x = $('.hidden')
you get all elements with class 'hidden'. .val() then gets the value from the first.
You need to limit the hidden input to the one on the same row as the delete button.
Unfortunately, your current hidden is not actually inside the table and you have this:
<table><tr>...</tr><tr>..</tr>
<input type="hidden"...>
<input type="hidden"...>
You need to change your markup to:
<tr>
<td><?php echo $product->getName(); ?></td>
<td><?php echo $product->getCategory(); ?></td>
<td><?php echo $product->getPrice().ProductController::coin; ?></td>
<td><?php echo $product->getNrProducts(); ?></td>
<td>
<button type="submit" value="Delete" class="upload" onclick="deleteDataTable();">Delete</button>
<input type="hidden" name="hiddenfieldname" class="hidden" value="<?php echo $product->getId();?>">
</td>
</tr>
or similar so that the input is inside a td.
You can then use relative elements on the delete click:
function deleteDataTable()
{
var x = $(this).closest("tr").find(".hidden").val();
}
or, using the amended html above, use .next but I would keep the above
var x = $(this).next(".hidden").val();
Maybe you are looking for this:
var x=[];
$('.hidden').each(function(){
x.push($(this).val());
});
x should contain all the values.
You can simply use this:
<tr>
<td><?php echo $product->getName(); ?></td>
<td><?php echo $product->getCategory(); ?></td>
<td><?php echo $product->getPrice().ProductController::coin; ?></td>
<td><?php echo $product->getNrProducts(); ?></td>
<td>
<button type="submit" value="Delete" class="upload getValue" data-product-id="<?php echo $product->getId();?>">Delete</button>
</td>
</tr>
<script>
$('.getValue').click(function(){
var val = $(this).data('product-id');
});
</script>
You can like that
<table cellspacing="0" cellpadding="0" id="product">
<tr>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th colspan="2">Nr products</th>
</tr>
<?php foreach ($productsInStock as $product) : ?>
<tr data-productid="<?php echo $product->getId();?>">
<td><?php echo $product->getName(); ?></td>
<td><?php echo $product->getCategory(); ?></td>
<td><?php echo $product->getPrice().ProductController::coin; ?></td>
<td><?php echo $product->getNrProducts(); ?></td>
<td><button type="submit" value="Delete" class="upload" onclick="deleteDataTable();">Delete</button></td>
</tr>
<?php endforeach; ?>
</table>
Script
function deleteDataTable()
{
var productIdOfCurrentTR = $(this).closest("tr").data("productid");
}

jQuery table td click not working properly

I have php code which generates a table. Inside td I have inserted img. When user click on td then it changes img inside it. But it is not working properly. Only even rows td element changes image while odd rows doesn't. Below is my code:
<div class="row" id="atten_list">
<div class="col-sm-offs-3 col-md1-6">
<table class="table table-bordered">
<thead>
<tr>
<td><?php echo get_phrase('roll');?></td>
<td><?php echo get_phrase('name');?></td>
<td><?php echo get_phrase('1');?></td>
<td><?php echo get_phrase('2');?></td>
<td><?php echo get_phrase('3');?></td>
<td><?php echo get_phrase('4');?></td>
<td><?php echo get_phrase('5');?></td>
<td><?php echo get_phrase('6');?></td>
<td><?php echo get_phrase('7');?></td>
<td><?php echo get_phrase('8');?></td>
<td><?php echo get_phrase('9');?></td>
<td><?php echo get_phrase('10');?></td>
<td><?php echo get_phrase('11');?></td>
<td><?php echo get_phrase('12');?></td>
<td><?php echo get_phrase('13');?></td>
<td><?php echo get_phrase('14');?></td>
<td><?php echo get_phrase('15');?></td>
<td><?php echo get_phrase('16');?></td>
<td><?php echo get_phrase('17');?></td>
<td><?php echo get_phrase('18');?></td>
<td><?php echo get_phrase('19');?></td>
<td><?php echo get_phrase('20');?></td>
<td><?php echo get_phrase('21');?></td>
<td><?php echo get_phrase('22');?></td>
<td><?php echo get_phrase('23');?></td>
<td><?php echo get_phrase('24');?></td>
<td><?php echo get_phrase('25');?></td>
<td><?php echo get_phrase('26');?></td>
<td><?php echo get_phrase('27');?></td>
<td><?php echo get_phrase('28');?></td>
<td><?php echo get_phrase('29');?></td>
<td><?php echo get_phrase('30');?></td>
<td><?php echo get_phrase('31');?></td>
</tr>
</thead>
<tbody>
<?php
$students = $this->db->get_where('student' , array('class_id'=>$class_id))->result_array();
foreach($students as $row):
?>
<tr class="gradeA" id="adata">
<td><?php echo $row['roll'];?></td>
<td><?php echo $row['name'];?></td>
<?php
for($i=1; $i<=31; $i++){ ?><?php
$datea = $i;
$full_date = $year.'-'.$month.'-'.$datea;
//inserting blank data for students attendance if unavailable
$verify_data = array( 'student_id' => $row['student_id'],
'date' => $full_date);
$query = $this->db->get_where('attendance' , $verify_data);
if($query->num_rows() < 1){
$this->db->insert('attendance' , $verify_data);}
//showing the attendance status editing option
$attendance = $this->db->get_where('attendance' , $verify_data)->row();
$status = $attendance->status;
$id = $attendance->attendance_id;
?>
<?php if ($status == 1):?>
<td align="center" id="status" title="<?php echo $id; ?>">
<img src="<?php echo base_url("/assets/images/present.png"); ?>" alt="StackOverflow" title="StackOverflow is the best!" />
</td>
<?php endif;?>
<?php if ($status == 2):?>
<td align="center" id="status" title="<?php echo $id; ?>">
<img src="<?php echo base_url("/assets/images/absent.png"); ?>" alt="StackOverflow" title="StackOverflow is the best!" />
</td>
<?php endif; ?><?php }?><?php $this->db->where('class_id',$class_id);
$this->db->from('student');
$nofs = $this->db->count_all_results(); ?>
<!-- Script for changing image on td click -->
<script>
$("table tbody tr#adata td#status").click(function() {
var img = $(this).find("img")[0];
if(img.src == '<?php echo base_url("/assets/images/present.png"); ?>'){
img.src = img.src.replace('<?php echo base_url("/assets/images/present.png"); ?>', '<?php echo base_url("/assets/images/absent.png"); ?>');
}
else if(img.src == '<?php echo base_url("/assets/images/absent.png"); ?>'){ img.src = img.src.replace('<?php echo base_url("/assets/images/absent.png"); ?>', '<?php echo base_url("/assets/images/present.png"); ?>');
}else{}
}); </script>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
Try this syntax ,
$('table').on('click','td',function(){
//Your code
});
Also use 'class' since 'ID' attrib should be unique

Result of document.getElementById in loop remain same

<?php for($i=0; $i< mysqli_num_rows($result); $i++){ ?>
<table id="t01" style="width:100%">
<tr>
<th colspan="2"><?php print_r($results[$i]['arr_question']); ?></th>
</tr>
<tr>
<td><?php print_r($results[$i]['a']); ?></td>
<td><?php print_r($results[$i]['b']); ?></td>
</tr>
<tr>
<td><?php print_r($results[$i]['c']); ?></td>
<td><?php print_r($results[$i]['d']); ?></td>
</tr>
<tr>
<td colspan="2"><button type="button" onClick="document.getElementById('').innerHTML= '<?php print_r($results[$i]['answer']); ?>'"> Answer </button>
<p id=''></p>
</td>
</tr>
<tr> <td colspan="2"><?php print_r($results[$i]['description']); ?></td>
</tr>
</table>
</br>
<?php } ?>
In this code document.getElementById('').innerHTML is not working properly, it returns the same value while clicking on button in loop, when i put id equals $i it return the value in same place at every loop, it overrides the data at same place, when i put any static value it returns same. What should i do for getting the different value at different places. Any help will be appreciable.
You cannot have empty ids, assign an id as follows:
<p id='p-<?php echo $i; ?>'></p>
And use it as follows in the query selector:
<button type="button" onClick="document.getElementById('p-<?php echo $i; ?>').innerHTML= '<?php print_r($results[$i]['answer']); ?>'"> Answer </button>

HTML Tags not rendered properly when passing to view PHP-JS

Hi i am using codeigniter framework ,
i am using an ajax request to get data from db and to show in view.
var from_date = jQuery('#form_date').val();
var to_date = jQuery('#to_date').val();
jQuery.ajax({
url:base_url+"index.php/eod_report/search_to_date",
type:"POST",
data:{from_date:from_date,to_date:to_date},
//datatype:'json',
success:function(data){
jQuery("#report_container").html(data);
}
my controler is
public function search_to_date()
{
$from_date = $this->input->post('from_date');
$to_date = $this->input->post('to_date');
$where_array = array('eod.created_time >='=>$from_date,'eod.created_time <='=>$to_date);
$eod_report_data = $this->eod_data->get_eod_report_data($where_array);
$eod_total_report_data = $this->eod_data->get_eod_total_report_data($where_array);
$formated_eod_report_data = $this->format_eod_report_array($eod_report_data);
krsort($formated_eod_report_data);
$formated_eod_all_report_data= $this->format_all_eodreport_array($eod_total_report_data);
krsort($formated_eod_all_report_data);
$data = array('eod_data'=>$formated_eod_report_data,'eod_all_data'=>$formated_eod_all_report_data);
$html = $this->load->view('eod-report-partial',$data,true);
echo json_encode($html);
}
eod-report-partial view
<table width="100%" align="center" border="1">
<thead>
<tr>
<td>ShopCode</td>
<td>Submitted By</td>
<td>RMS</td>
<td>ORM</td>
<td>ORM Profit</td>
<td>Total</td>
<td>Cash</td>
<td>Card</td>
<td>Opening Balance</td>
<td>Purchase Today</td>
<td>Final Total</td>
<td>T.Till Cash</td>
<td>Difference</td>
<td>Nxt Day Op Balance</td>
<td>Petty Cash</td>
<td>Banking</td>
</tr>
</thead>
<tbody>
<?php foreach($eod_data as $key=>$eods) {?>
<tr><td colspan="8""><?php echo $key; ?></tr>
<?php foreach($eods as $eod) { ?>
<tr>
<td><?php echo $eod['shop_code']; ?></td>
<td><?php echo $eod['first_name']; ?></td>
<td><?php echo $eod['rms_sell'];?></td>
<td><?php echo $eod['orm_repair']; ?></td>
<td><?php echo $eod['orm_repair'];?></td>
<td><?php echo $eod['total']; ?></td>
<td><?php echo $eod['cash']; ?></td>
<td><?php echo $eod['card']; ?></td>
<td><?php echo $eod['opening_bal']; ?></td>
<td><?php echo $eod['purchases']; ?></td>
<td><?php echo $eod['final_total']; ?></td>
<td><?php echo $eod['till_total']; ?></td>
<td><?php echo $eod['difference']; ?></td>
<td><?php echo $eod['nextday_opening_bal']; ?></td>
<td></td>
<td><?php echo $eod['banking']; ?></td>
</tr>
<?php } ?>
<tr>
<td></td>
<td>Total:</td>
<td><?php echo $eod_all_data[$key]['sum_rms_sell'];?></td>
<td><?php echo $eod_all_data[$key]['sum_orm_repair']; ?></td>
<td><?php echo $eod_all_data[$key]['sum_orm_repair'];?></td>
<td><?php echo $eod_all_data[$key]['total']; ?></td>
<td><?php echo $eod_all_data[$key]['sum_cash']; ?></td>
<td><?php echo $eod_all_data[$key]['sum_card']; ?></td>
<td><?php echo $eod_all_data[$key]['sum_opening_bal']; ?></td>
<td><?php echo $eod_all_data[$key]['sum_purchases']; ?></td>
<td><?php echo $eod_all_data[$key]['final_total']; ?></td>
<td><?php echo $eod_all_data[$key]['sum_till_total']; ?></td>
<td><?php echo $eod_all_data[$key]['difference']; ?></td>
<td><?php echo $eod_all_data[$key]['sum_next_day_bal']; ?></td>
<td></td>
<td><?php echo $eod_all_data[$key]['sum_banking']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
the problem is the view rendering to the page is
how to render my html properly , thanks in advance
You need to decode the json object before setting it as the html in the container.
var html_data = jQuery.parseJSON(data);
jQuery("#report_container").html(html_data);
Please note the use of jQuery.parseJSON function for backwards compatibility for browsers that don't have a JSON object.
Also you have a typo in your from_date variable. It reads #form_date where it should read #from_date.
EDIT
Here's a dirty way to deal with it for now:
html_data = jQuery.parseJSON(data);
html_data = html_data.replace("\r\n", "").replace("\", "");
jQuery("#report_container").html(html_data);

Categories

Resources