Get value from table when clicking on a button - php

I have a table there is showing some values. In each row there is a Order_ID and a button.
How can i get my value in $Order_ID to show (alert) when clicking on a button?
<tbody>
<?php
foreach($menuextra_result as $transaction)
{
?>
<tr>
$order_id = isset($transaction['order_id'])?($transaction['order_id']) :"";
?>
<?php if($order_id){ ?>
<td><div id="orderID"><?= $order_id ?></a></td>
<?php } else {?>
<td><div ><span style="color:red">MANGLER</span></td>
<?php }?>
style="color:red">MISSING</span></td>
<?php }?>
//There's more here, but did not bother to show it, because it was irrelevant.
<td><input type="submit" onclick="getElementById" value="Yes "></td>
<?php }
?>
</tr>
<?php
}
?>
</tbody>
This is how i tried
<script type="text/javascript">
function getElementById()
{
el = document.getElementById('order_id');
alert(el);
}
</script>
But when clicking on a button, nothing happens

table.php
//assuming you have done you loop work
<table>
<tr>
<td>
<?php echo $row['name']?>
</td>
<td><input type="button" value="click me" onclick="clickMe(<?php echo $row['id']?>)" /></td>
</tr>
</table>
clickme unction is like this
function clickMe(id) {
alert(id);
}
You will pass one parameter to clickMe() function and the parameter is id

First of all, don't use id as you have more than one such element. You can use class instead:
<div class="orderID"><?= $order_id ?></div>
Also fixed invalid HTML you got, closing tag for <div> is </div> and not </a>.
Second, change the click to send the button to the function:
<input type="submit" onclick="FindOrder(this);" value="Yes " />
And finally this function should do the trick: (by searching for "brother" div)
function FindOrder(oButton) {
var oRow = oButton.parentNode;
while (oRow && oRow.tagName.toLowerCase() !== "tr")
oRow = oRow.parentNode;
var arrDivs = oRow.getElementsByTagName("div");
var orderDiv = null;
for (var i = 0; i < arrDivs.length; i++) {
if (arrDivs[i].className === "orderID") {
orderDiv = arrDivs[i];
break;
}
}
if (orderDiv != null) {
var orderNumber = orderDiv.innerHTML;
alert("order is " + orderNumber);
} else {
alert("order not found");
}
}
Live test case.

You'll need to print the $order_id to your HTML somewhere. You could use hidden input:
<input name="order_id" id="order_id" value="<?php echo $order_id; ?>">
Then you can submit form or grab the value.

You can't getElementById from you web page if it does not exist.
So solution is simple, just add an hidden input element on your table. You can get the id from your script.
<tbody>
<?php
foreach($menuextra_result as $transaction)
{
?>
<tr>
<?php
$order_id = isset($transaction['order_id'])?($transaction['order_id']) :"";
?>
//There's more here, but did not bother to show it, because it was irrelevant.
<td>
<input type="hidden" name="order_id" id="order_id" value="<?php echo $order_id;?>">
<input type="submit" onclick="getElementById" value="Yes "></td>
<?php }
?>
</tr>
<?php
}
?>
</tbody>

Related

Get selected Dropdown value - PHP

I have a dropdown populated with values I get from the database.
I need to perform some queries based on the selected option, but first I need to save the selected value on a new variable.
This is my dropdown:
<form name="dashboard_form" action="" id="dashboard_form" method="post">
<tr>
<td><?php _e('Select City')?>:</td>
<td>
<select class="selected_city" name="selected_city" style="margin: 20px;width:300px;" required>
<?php
foreach ( $all_cities as $city )
{
echo '<option value='.$city->ID.'>'.$city->name.'</option>';
}
?>
</select>
</td>
</tr>
</form>
*$all_cities is an array with all the cities.
My jQuery:
<script>
jQuery("#dashboard_form").validate({
ignore:'',
rules: {
'selected_city': {
required: true
}},
messages: {
'selected_city': "Please Select a City",
},
errorPlacement: function(error, element) {
jQuery(element).closest('tr').next().find('.error_label').html(error);
}
});
</script>
How can I save on a $new_variable my selected value from the dropdown?
EDIT 1:
I added the following to
$(document).ready(function () {
var selected_city;
$('.selected_city').change(function() {
selected_city = $(this).val();
alert(selected_city);
});
});
The alert(selected_city) prints the correct city, how can I use this selected_city on the PHP?
EDIT2:
The problem is the dropdown is not submitting anything, so I created a Button to force it to Submit:
<input type="submit" value="<?php _e('Send Now')?>" name="send_now_button" id="send_now_button" class="button button-primary">
Then:
if(isset($_POST['send_now_button'])){
if(isset($_POST['selected_city'])) { $selected_city = $_POST['selected_city']; } else {$selected_city = 'Lisboa'; } }
Now when I echo $selected_cities_id; it gives the correct value!
Your HTML is invalid. <tr> can't be the child of <form>, it has to be the child or <table>, <tbody>, <thead>, or <tfoot>. This could be preventing the <select> from being treated as part of the form, so nothing is being submitted.
You need to put the form around the entire table.
<form name="dashboard_form" action="" id="dashboard_form" method="post">
<table>
...
<tr>
<td><?php _e('Select City')?>:</td>
<td>
<select class="selected_city" name="selected_city" style="margin: 20px;width:300px;" required>
<?php
foreach ( $all_cities as $city )
{
echo '<option value='.$city->ID.'>'.$city->name.'</option>';
}
?>
</select>
</td>
</tr>
...
</table>
</form>

Ajax Posted data not being read by $_POST in php

I am trying to post the value of fields in a table through Ajax to process.php that will process the data.
the table:
<form name="items">
<table width="90%" border="1">
<tbody>
<tr>
<td width="26%">Item Name</td>
<td width="22%">If other then give name</td>
<td width="22%">Quantity</td>
<td width="16%">$/Unit</td>
<td width="14%">Total</td>
</tr>
<?php for ($i = 1; $i <= 10; $i++) {
?>
<tr>
<td>
<select name='itemname<?php echo $i;?>' id='itemname<?php echo $i;?>'>
<option value="other">other</option>
<?php
$qry_item_name = "SELECT DISTINCT item_name FROM bus_name_details";
$result_item_name = mysql_query($qry_item_name);
while($row_item_name = mysql_fetch_array($result_item_name)) {
$option .="<option>" . $row_item_name['item_name'] . "</option>";
echo $option;
}
?>
</select>
</td>
<td>
<input type="text" name="other<?php echo $i;?>" id="other<?php echo $i;?>"></td>
<td>
<input type="text" name="quan<?php echo $i;?>" id="quan<?php echo $i;?>" value="0"></td>
<td><input type="text" name="unit<?php echo $i;?>" id="unit<?php echo $i;?>" onkeyup="calculateTotal('<?php echo $i;?>')"></td>
<td><span name="total<?php echo $i;?>" id="total<?php echo $i;?>"></span></td>
</tr>
<?php }?>
</tbody>
</table>
</form>
<span id="subm3" class="subm3" >Submit </span>
The Ajax:
<script>
$(document).on('click', '.subm3', function() {
var datas = {};
for ($i = 1; $i < 2; $i++) {
// drop down list of items
datas["item_name"+$i]= $('#itemname'+$i+' option:selected').attr('value')
// other name
datas["other"+$i]= $('input[name=other'+$i+']').val()
// quantity
datas["quan"+$i]= $('input[name=quan'+$i+']').val()
// price per unit
datas["unit"+$i]= $('input[name=unit'+$i+']').val()
}
$i = $i_limit-1;
$.ajax({
url: 'parts/process.php?order=3&items='+$i,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(datas)
});
});
</script>
then the process :
<?php
if ($order==3){
$loop = $_GET[items];
$other1= $_POST["other1"];
echo "other1 = ".$other1;
}
?>
On chrome inspector i get that the data was sent like this as source :
{"item_name1":"other","other1":"Water Valve","quan1":"2","unit1":"2"}
and like this as parsed :
item_name1: "other"
other1: "Water Valve"
quan1: "2"
unit1: "2"
but the response from process.php (the one that got the values) seems to only have read the get values but not the post values :
other1 =
i am pretty much new to ajax and hope someone could help point me to where i am going wrong here. This might not even be the easiest or best way of doing what i am trying to do, but it kind of makes sense to my brain at the moment so i am taking this route. Any help is appreciated
can you try data:datas insted of data: JSON.stringify(datas) in ajax request
ref: how to send multiple data with $.ajax() jquery

How to Insert to database from loop Using PHP?

The problem occurs when I insert without data. So I want your help in solving this problem.
This is my file:
students.php
<form id="student_form" method="POST" action="">
<?php
if(mysql_num_rows($q)>0){
?>
<table border="0" dir="ltr" align="center"cellpadding='0' cellspacing='0' >
<tr> <th>Student ID</th><th>Name</th><th>AVG</th><th>Joining Year</th><th>Message</th><th>Sending Message</th> </tr>
<?php while($row = mysql_fetch_array($q)){ ?>
<tr>
<td id="stud_id[]"> <?php echo $row['studant_ID']; ?></td>
<td> <?php echo $row['studant_Name']; ?></td>
<td> <?php echo $row['Average']; ?></td>
<td> <?php echo $row['year']; ?></td>
<td> <input id="message1[]" name="message1[]" type="text" size="25px" /></td>
<td><input name="submit[]" id="submit[]" type="submit" value="Send" /> </td>
</tr>
<?php }}
and this is my insert file:
insert_message.php
if (isset($_POST['message1']) && $_POST['message1']!='') {
$addss = mysql_real_escape_string($_POST['message1']);
}
if (isset($_POST['stud_id']) && $_POST['stud_id']!='') {
$std_id = mysql_real_escape_string($_POST['stud_id']);
}
//#######################################################################
$query1 = "INSERT INTO `message` (`rcvrid`, `senderid`, `msg`) VALUES ('$std_id', '22011111', '$addss'); ";
mysql_query($query1);
I connect between two file by jquery and ajax.
<script>
$("#student_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_message.php",
data: $(this).serialize(),
success: function(data) {
$("#inner_contant").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
Remove the form from the page
<tr>
<td id="stud_id"> <?php echo $row['studant_ID']; ?>
<input type="hidden" name="stud_id" value="<?php echo $row['studant_ID']; ?>"/>
</td>
<td> <?php echo $row['studant_Name']; ?></td>
<td> <?php echo $row['Average']; ?></td>
<td> <?php echo $row['year']; ?></td>
<td> <input id="message1" name="message1" type="text" size="25px" /></td>
<td><button class="submit" type="submit" />Send </button> </td>
</tr>
second:
your js should look like this:
$(".submit").on("click", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_message.php",
data: {stud_id:$(this).closest('tr').find('input[name="stud_id"]').val(),message1:$(this).closest('tr').find('input[name="message1"]').val()},
success: function(data) {
$("#inner_contant").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
In insert_message.php
you need to echo a message to see if you where succesful in updating the database
echo json_encode(array('message'=>'Data updated/Error'));
First of all - all data passed to server in a $_POST array is taken from input fields with name attribute (unless you have some custom js handlers).
So
<td id="stud_id[]"> <?php echo $row['studant_ID']; ?></td>
does nothing.
If you want to store studant_ID somehow - use hidden field for example:
<td>
<input type="hidden" name="stud_id[]" value="<?php echo $row['studant_ID']; ?>" />
</td>
Next - what do you want from this buttons:
<input name="submit[]" id="submit[]" type="submit" value="Send" />
As they are all belong to one form they will do the same - send all fields to server. If you want every submit button send to server only a pair student_id, message you have to create a form for each pair (or do some js-handlers). Otherwise, on your server you'll have:
$_POST['stud_id'] array of all students ids from form
$_POST['message1'] array of all messages from form
If you want to process them all - do a foreach:
foreach ($_POST['stud_id'] as $key => $id) {
// find the message
$msg = $_POST['message1'][$key];
$query1 = "INSERT INTO `message` (`rcvrid`, `senderid`, `msg`) VALUES ('$id', '22011111', '$msg'); ";
mysql_query($query1);
}
And of course you should remove mysql_ functions and use newer apis - PDO or mysqli

PHP Passing Input values through href to another page

<input type="text" name="a" id="a" />
CLICK
Now this is my question that can we pass an input tag value of HTML to 'mk' so that value can be used in the next page for process.
Though i have done my project in a different way but still i want to know wether is it possible to do so .
I have searched a lot but none of the question is same as i got so plz help me out.
And i dnt want to use form so i just want to know can we pass this value using href tag r not.
This is the code i have
<form method="post">
<table align="center" bgcolor="#FFFFCC" border="1">
<tr><th>ID</th><th>PRODUCT</th><th>PRICE</th><th>DATE OF POST</th><th>PHONE NUMBER</th><th>AUTHENTICATE</th></tr>
<?
$sel = mysql_query("SELECT * FROM addunauth WHERE adminauthorize = 'uncheck'") or die("CANNOT FETCH DATA FOR ADMIN " . mysql_error());
if (mysql_num_rows($sel) > 0) {
while ($data = mysql_fetch_array($sel)) {
?> <tr>
<td><? echo $data['id']; ?></td>
<td><? echo $data['product_name']; ?></td>
<td><? echo $data['product_sp']; ?></td>
<td><? echo $data['product_time']; ?></td>
<td><? echo $data['phoneNumber']; ?></td>
<td><input type="text" name="a" id="a" /></td>
<td align="center">
<a href="processadminTask.php?id=<? echo $data['id']; ?>&mk=" >
AUTHENTICATE
</a>
</td>
</tr>
<?
}
} else {
?> <tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>
<? }
?>
</table>
</form>
Now just tell me how to pass the input value
Your variable not parse inside single quotes. your <? echo '$data['id']' ?> should be <?php echo $data['id'] ?>
<input type="text" name="a" id="a" />
CLICK"
<a id="link" href="xxx.php?id=111&mk=">CLICK</a>
Edit:-
simply add one more hidden fields to store id value as well and get value in js and assign to href
<input type="text" name="idval" id="idval" value="100" />
<input type="hidden" name="mk" id="mkval" value="101" />
Js:-
var idval = $('#idval').val();
var mk = $('#mkval').val();
var link = 'xxx.php?id=' + idval + '&mk=' + mk;
$("#link").attr("href", link);
Working Demo
<? echo '$data['id']' ?>
Is wrong PHP Syntax
Use
<?php echo $data['id']; ?>
Like:
CLICK
Your
<? echo '$data['id']' ?>
is not correct. You can actually use something like this
<?= $data['id'] ?>
so you'll have
CLICK"
I think it is possible with javascript:
getElementById('id of html input').value
This will get you the input value and then you can assign it to 'mk'
So you can check with it
Try this
<?php
$data['id'] = 2;
?>
<html>
<input type="text" name="a" id="a" />
CLICK
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script >
$(document).ready(function(){
$('a[href]').click(function(event){
event.preventDefault();
event.stopPropagation();
var inputTagID = $('#a').val();
var hrefVal = this.toString().replace("&mk=", "&mk="+inputTagID);
window.location = hrefVal;
});
});
</script>
</html>

jquery data attribute with input selector in a loop

I have an html table built from a database query which loops through and creates a button for each camera name found and puts them in a table:
<?php
for($i=0;$i<$num_rows;$i++)
{
?>
<tr>
<td>
<input type="submit" class="play" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">
</td>
</tr>
<?php
}
?>
This resolves to something like this:
<tr>
<td>
<input type="submit" class="play" data-hash="0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5" value="Office Window">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="b824cba374c3d5ab7806ad8260c939323c03147b" value="aaa">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="ec9658f0c1855e2e2ac09ae284f5e6990dbf445d" value="laptop">
</td>
</tr>
Notice the data hash attribute is different for each button. I want to process this button with my jquery code:
$(".play").click(function(){
var camerahash = $('input').data('hash');
console.log($('input').data('hash'));
});
No matter which button I click I will always get the hash from the first button I click: 0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5. Any help is appreciated.
$('input').data('hash') gives you the data attribute of the first input in the selection use $(this).data('hash') to get the data attribute of the currently clicked input
You need to specify which input element to read.
Try something like:
$(".play").click(function(){
$this = $(this);
var camerahash = $this.data('hash');
console.log($this.data('hash'));
});
You are always calling the first object of .play. This would be a correct way:
$('.play').on('click', function(){
var camerahash = $(this).data('hash');
});
You could always grab them by using the .attr(data-hash) html5 attribute.
Try:
$('.play').on('click', function() {
var _hash = $(this).attr('data-hash');
console.log(_hash);
});
Your selector will return the first one that it comes to. Use this instead
<script>
$("input.play").click(function() {
alert($(this).data('hash'));
});
</script>

Categories