php insert button value for user - php

i have a table where i print out all of the users for the program. now i would like to have a toggle Bootstrap button for Activate and Incative. I would like to store 1 and 0 into my database. how do i save the value for the specific User ID the value and then update it when the button pressed. Also how to then when it has been pressed to then update the page? is it possible to not refresh the page?
<div class="table-responsive-sm">
<table class="table table-bordered table-condensed table-striped text-center table-dark">
<tr>
<th> First Name</th>
<th>Last Name</th>
<th>E-mail</th>
<th>Username</th>
<th>Accreditation</th>
<th>Instructor ID</th>
<th>Time Registered</th>
<th>Account State</th>
<th>Activate</th>
<th>SET Inactive</th>
</tr>
<?php
$sql = ("SELECT * FROM instructors GROUP BY ID ORDER BY ID DESC ");
$result=mysqli_query($mysqli,$sql);
while ($row=mysqli_fetch_array($result)){
$accred = $row['role'];
if($accred == '0'){
$test = 'Admin';
} else if ($accred == '1') {
$test = 'Bookkeper';
} else if ($accred == '2') {
$test = 'Coordinator';
} else if ($accred == '3') {
$test = 'Instructor';
}
$LoginState = $row['LoginState'];
if($LoginState == '0'){
$LogState = '<td style="color: White; background-color: orangered"><b>Inactive</b></td>';
} else if ($LoginState == '1') {
$LogState = '<td style="color: black; background-color: lightgreen"><b>Active</b></td>';
}
$ID = $row['ID' ];
echo "
<form method=\"POST\">
<tr>
<td>".$row['Fname']."</td>
<td>".$row['Lname']."</td>
<td>".$row['Email']."</td>
<td>".$row['username']."</td>
<td>".$test ."</td>
<td>".$row['ID' ] ."</td>
<td>".$row['RegisteredTime']."</td>
$LogState
<td><button name=\"LoginState\" type=\"button\" class=\"btn btn-success\" role=\"button\" value\"1\">Activate</button</td>
<td><button name=\"LoginState\" type=\"button\" class=\"btn btn-warning\" role=\"button\" value\"0\">SET Inactive</button</td>
</tr></form>";
}
if (isset($_POST['LoginState'])){
$sql1 = "INSERT into instructors (LoginState) VALUES ($logstats) WHERE ID = $ID";
if ($mysqli->query($sql1) === TRUE) {
echo "New record created successfully";
echo "<br/>";
} else {
echo "Error: " . $sql1 . "<br>" . $mysqli->error;
}}

Here is the html code to show toggle button
<td data-title="Status">
<label class="switch">
<input type="checkbox" id="toggle<?php echo $id; ?>" name="status_<?php echo $id; ?>" <?php if($status == 'on'){echo "checked"; }?> >
<div class="toggle round"></div>
</label>
</td>
$id is dynamic id which you get from db.you need proper CSS these classes to make it toggle button.
AJAX call to update records in db onChange of checkbox value
<script type="text/javascript">
$(document).ready(function(){
$('#toggle<?php echo $id; ?>').click(function(){
var id = <?php echo $id; ?>;
if($(this).prop("checked") == true){
var stat = 'on';
}
else if($(this).prop("checked") == false){
var stat = 'off';
}
$.ajax({
type: "POST",
url : "example.php",
data : { id : id,stat :stat },
success: function(data) {
//update value in page acc to new updated value from db
}
});
});
});
</script>
$id is same as above. You need to do update then select query in example.php to update content in page, without refreshing the page

Mark, as others said, if you want to refresh part of your page without reloading the whole page, you need to use AJAX.
One of the most popular and simple way to use AJAX is including the jQuery.js library. If you already use javascript, you will find a bit easy to include jQuery in your page. (you can find and copy the jquery.js file anywhere on internet, just type "download jquery file" in google)
in example, you can put this code in your html (in fact, you can put it almost in any place of your page)
<script type="text/javascript" src="jquery.min.js"></script>
Then you can use the softech's example...
<script type="text/javascript">
$(document).ready(function(){
...
$.ajax({
type: "POST",
url : "PageThatOnlyReturnsData.php",
data : { id:id, stat:stat },
success: function(data) {
//update value in page acc to new updated value from db
}
});
...
});
</script>
It's strongly recommended thay you create another php page to place de mySQL code and returns data (I named in example "PageThatOnlyReturnsData.php"), so this php page will print out the result data from your query.
So, the front php (the first page with HTML) calls the second php (the data php) through the $.ajax() function, and you can process the received data within the "success" function.
success: function(data) {
//here "data" is what you receive from the second php
//do what you want here with javascript using the new variable "data" as in the softech's example
}

Related

PHP: Update database with checkbox values for each row

I'm currently working on displaying a table containing a list of alarms, where each row contains a checkbox that determines whether the user has already viewed that alarm or not. Here's
an image:
So far, I managed to check/uncheck the checkbox given its state in the database. What I want to do, and don't exactly know how to, allow the user to check/uncheck a checkbox and immediately update the database with this new state without pressing a submit button. The code that I have right now is the following.
<div class="card-body table-responsive p-0">
<form action=modules/alarms.php method="POST">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Tipus</th>
<th>Data</th>
<th>Vista</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result->fetchAll() as $row){
if ($row[4] == 1){
$status = "checked";
}else{
$status = "";
}
echo
'<tr data-widget="expandable-table" aria-expanded="false">
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
<td><input type="checkbox" name="chk1[]" value="viewed" '.$status.'></td>
</tr>
<tr class="expandable-body">
<td colspan="5">
<p>
<video width="416" height="416" controls>
<!-- el 42 es la cabecera C:/... fins videos-->
<source src="'.substr($row[3], 42).'" type="video/mp4">
Your browser does not support the video tag.
</video>
</p>
</td>
</tr>';
}
?>
</tbody>
</table>
And the PHP code I have (I don't have the code that will update values on the database, but I'll figure that out. I want to know how I could retrieve the value of the checkbox of every row and its ID so I can update it on the database.
$ei = $_POST['chk1'];
if ($_POST["chk1"] == "chk1") {
for ($i = 0; $i < sizeof($checkbox1); $i++) {
print_r($checkboxl[$i]);
}
}
To solve this problem, first I had to add some fields to the checkbox input. WIth those changes, the table is generated as it follows:
<tr data-widget="expandable-table" aria-expanded="false">
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
<td><input type="checkbox" name="id" id="viewed" value="'.$row[0].'" '.$status.'></td>
</tr>
After this is done, simply add a script that will retrieve the values from the clicked checkbox and pass them to the necessary PHP function:
$("input").change(function() {
if ($(this).is(':checked')){
var viewed=1;
}else{
var viewed = 0;
}
var id = $(this).val();
$.ajax({
url:"modules/alarms.php",
method:"POST",
data:{viewed:viewed,id:id,},
success: function(data){
},
});
Please note that the 'url' field is the relative path where our PHP function is implemented.
And now, simply update the database with the checkbox value (I'm using PDO objects) as it follows:
<?php
if(isset($_POST["viewed"])) {
$id = $_POST["id"];
$viewed = $_POST["viewed"];
$sql="UPDATE `alarms` SET `viewed` = '$viewed' WHERE (`id` = '$id')";
if($connection->query($sql) === TRUE){
echo "Success";
} else {
echo "error" . $sql . "<br>".$connection->error;
}}?>

anchor tag to call pop up Modal Box without bootstrap not working?

I have a table with each row has link of tag "click here", I want to use a modal box to pop up when a user click on the link and display all row information and allow user to make edit and update.
I am using AJAX with JQuery to pass row id, which is used at backend with PHP to execute SQL Query.
But i don't want to use Bootstrap Modal Box. Please help in making a modal box pop up or something other so that user can make edits on each row of displayed table when a user click on <td><p><a href='' id='%d' value='%d'>Click here</a></p></td>.
I am not clear with how to use Modal Box for each row. may be that could be easier using Jquery.
Below is code of <section> tag of my Dashboard.html which has table.
Here focus on <td><p><a href='' id='%d' value='%d'>Click here</a></p></td>. which include button to call modal box.
<!-- View All Added Campaign and Lead information -->
<section class="operation" id="view_all_lead_Campaign" style="width: 100%;margin: 0 auto; display: none;">
<!-- Main Tables Campaign and Lead Table -->
<div class="row">
<!-- MAIN TABLE-->
<div class="col" >
<button class="viewMainTable" name='viewMainTable' onclick='viewMainTable();' id='viewMainTableButton' >Lead Table</button>
<button class="viewCampaignTable" name='viewCampaignTable' onclick='viewCampaignTable();' id='viewCampaignTableButton' >View Campaign Table</button>
<div class="row">
<div class="col span-4-of-4">
<div style="overflow-x:auto;">
<table class="display_table" id='main_lead_table' style="display: none;">
<thead>
<th>#</th>
<th>Lead Id</th>
<th>Name</th>
<th>Website</th>
<th>Linkedin</th>
<th>Lead Description</th>
<th>Owner Notes</th>
<th>Last Contact Date</th>
<th>Next Contact Date</th>
<th>Lead Status</th>
<th>Details</th>
</thead>
<tbody id='leadTable'>
<?php
function getLeadAddedByName($id){
include('./server/connection.php');
$selectSQL = "SELECT UserName FROM `tbl_user_signup_info` WHERE User_Id = '$id' ";
$result = $conn -> query ($selectSQL);
$name = "";
while($row = mysqli_fetch_array($result)){
$name = $row['UserName'];
}
return $name;
}
include('./server/connection.php');
$selectSQL = "SELECT * FROM `tbl_main_lead_info` ORDER BY Lead_Id";
$result = $conn -> query ($selectSQL);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
printf( "<tr class='content'>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><p><a href='' id='%d' value='%d'>Click here</a></p></td>
</tr>",
$i,
$row['Lead_Id'],
$row['FirstName']." ".$row['LastName'],
$row['Website'],
$row['Linkedin'],
$row['LeadDescription'],
$row['OwnerNotes'],
$row['AdminNotes'],
getLeadAddedByName($row['LeadAddedBy'])."<br>Date/Time: ".$row['LeadAddedOn'],
date('d-m-Y', strtotime($row['LastContactDate'])),
date('d-m-Y', strtotime($row['NextContactDate'])),
$row['LeadStatus'],
$row['Lead_Id'],
$row['Lead_Id'],
);
$i = $i+1;
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
Modal.js file to get the click here id and correspoding that PHP at backend execute to fetch record and populate in Modal Box Pop up.
$(document).ready(function() {
$('[name="leadidclick"]').click(function(e){
e.preventDefault();
var leadid = $('[name="leadidclick"]').val();
$.ajax({
type: "POST",
url: './server/modal.php',
data: {
'leadid': leadid
},
success: function(data){
var result = $.parseJSON(data);
console.log(result);
//Modal Box to POP UP HERE
}
});
});
});
My Modal.php file for backend
<?php
// send a JSON encoded array to client
include('./server/connection.php');
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
if( $_POST['campaignid'] != "" ) {
// echo "Modal.php file is executed";
$id = $_POST['campaignid'];
$selectSQL = "SELECT * FROM `tbl_main_lead_info` WHERE Lead_Id = '$id' ";
$result_array = array();
$result = $conn -> query ($selectSQL);
// If there are results from database push to result array
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
array_push($result_array, $row);
}
}
echo json_encode($result_array);
}else{
echo $conn->error;
}
Step 1:
Add a Modal in the page.
Step 2:
Upon click of the anchor element pass the id to ajax function and fetch record
Step 3:
create the form at either php or jquery side.
and show modal with the final response.
At PHP
response from server will have form ready with data, you just need to add the response to modal-body div.
$.ajax({
url :: 'your url',
type : 'post',
data : {id: row id},
success: function(response){
$('.modal-body').html(response);
$('#your-modal-id').modal('show');
}
});
At Jquery side
$.ajax({
url :: 'your url',
type : 'post',
data : {id: row id},
dataType: "JSON",
success: function(response){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#form-element').val(json[i].item_name);
.
.
.
}
$('#your-modal-id').modal('show');
}
});
Please note: there are many ways to do it, if you find it complex, feel free to write, I will try to give you exact solution. :)

SQL generated table in PHP, insert row into SQL only if user inputs correct ID

I have generated a table from a query and at the end of each row in the table there is a 'book' button. Once this button is selected, a modal asking the user to enter their ID is shown. Once the user enters their ID, a button is clicked and the ID is checked against the database.
What I would like to do is when the button is clicked within the modal have the selected row data and the members ID inserted into the database table. I'm getting confused on how I can get the selected row data after the modal is shown.
An image of php table:
Code for index.php
<table class="table table-bordered">
<tr>
<th width="10%">Class</th>
<th width="35%">Date</th>
<th width="40%">Time</th>
<th width="10%">Location</th>
<th width="5%">Book</th>
</tr>
<?php
while ($row = mysqli_fetch_array($sql)){
$classdescription = $row["class_description"];
$date = $row["date"];
$start = $row["startTime"];
$area = $row["area_description"];
?>
<tr>
<td><?php echo $classdescription?></td>
<td><?php echo $date?></td>
<td><?php echo $start?></td>
<td><?php echo $area?></td>
<td><input type="button" data-toggle="modal" data-target="#myModal" value="Book" name="book"/>
</td>'
</tr>
<?php
}
?>
</table>
</div>
</div>
<!-- Book Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Book Modal content-->
<form id = "bookingform" action="login.php" method="post">
Username: <input type="username" id="username" placeholder="username"></br>
<button id="book">Book</button>
</form>
code for login.php
<?php
$user = $_POST['user'];
require "connectivity.php";
$date = date("Y-m-d");
$query = "SELECT member_forename FROM member WHERE name='$user'";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
}
elseif (mysqli_num_rows($result) == 0) {
echo "Username not recogised";
}
$sql = "INSERT INTO booking (booking_id, booking_date, customer_ID, bschedule_date, bschedule_class_id) VALUES ('15', '$date', '3', '2017-12-32')";
if(mysqli_query($con, $sql)) {
echo "booking made";
}
?>
login.js
$(document).ready(function(){
$("#login_btn").click(function(){
var user = $("#username").val();
var data = "user=" + user;
$.ajax({
method: "post",
url: "login.php?",
data: data,
success: function(data){
$("#login_error").html(data);
}
});
});
This example is based on an example made on the site https://www.w3schools.com
I use PG_QUERYS but you can switch to MYSQL. The rest is what you want. Any doubt is just ask.
getuser.php
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$dbconn = pg_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect');
}
$query = "SELECT * FROM user WHERE id = $1";
$result = pg_prepare($dbconn, "my_query", $query);
$data = array($q);
$result = pg_execute($dbconn, "my_query", $data);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = pg_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "</tr>";
}
echo "</table>";
pg_close($dbconn);
?>
</body>
</html>
The Html
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
This is a simple example, for you to understand the basics. If you want more help start programming, and if you have any difficulties ask the community.
In the example above, when a user selects a person in the dropdown list above, a function called "showUser()" is executed.
The function is triggered by the onchange event.
Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and exit the function. If a person is selected, do the following:
1) Create an XMLHttpRequest object
2) Create the function to be executed when the server response is ready
3) Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a preaper execute on a PostgreSQL database, and returns the result in an HTML table.
Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:
1) PHP opens a connection to a PostgreSQL server
2) The correct person is found
3) An HTML table is created, filled with data, and sent back to the "txtHint" placeholder.
What you want is to have the ID of the selected row in the modal, so that you can include it in the form and submit it to the login script. As I see it there are several approaches how you can achieve that.
One is to dynamically generate an individual modal for each row that includes its ID. Here you would move the modal code into the while loop and create a new modal for each row with an individual ID etc. The row ID should be included as hidden input in the form.
Another solution would be to use java script to keep track of which row has been selected. For that you need to
a) call a js function for each "book" button in the table that sets the row ID on a global JS var.
b) do the form submit with Java script and ensure the row ID is set first in the same script

How to get the value of the button in a table if it has multiple records

This is my following code in front End:
<div class="panel panel-primary">
<div class="panel-heading text-center text-uppercase">Birth Certificates For Overall (Pending, Completed)</div>
<div class="panel-body">
<div class="box-body">
<table id="viewer" class="table table-bordered">
<thead>
<tr>
<th>Sr No</th>
<th>Reg Number</th>
<th>From Hospital</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php $Viewer->showAllData(); ?>
</tbody>
<tfoot>
<tr>
<th>Sr No</th>
<th>Reg Number</th>
<th>From Hospital</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div>
This is my classes code in it of which i have called the object:
public function showAllData()
{
$query = "SELECT * FROM certificate_details ORDER BY created DESC";
$connection = $this->establish_connection();
$details = $connection->query($query);
$connection->close();
if($details->num_rows > 0)
{
$counter = 1;
while($detail = $details->fetch_assoc())
{
$status = $detail['status'];
if($status == 0)
{
$bg = "bg-danger";
$issuestatus = "btn btn-success";
$message = "Confirm Issue!";
}
elseif($status == 1)
{
$bg = "bg-success";
$issuestatus = "btn btn-success disabled";
$message = "Certificate Issued";
}
else
{
$bg = "bg-warning";
$issuestatus = "btn btn-warning";
}
echo "
<tr class='odd gradeX ".$bg."'>
<td>".$counter."</td>
<td>".$detail['registration_number']."</td>
<td>".$this->getHospitalInfo($detail['user_id'])."</td>
<td style='margin: 0;'><div class='btn btn-primary' href='#' value='".$detail['id']."' id='view-details'>View Details</div><div style='margin-left: 10px;' class='".$issuestatus."' href='#' value='".$detail['id']."' id='confirm-issue'>".$message."</div></td>
</tr>
";
$counter = $counter + 1;
}
}
}
I have give a specific id to the button i.e id="view-details" and in the value section it hold the unique value
This is the following JQuery Code which i am triggering whenever i am calling the ("#view-details").click(function(){})
$("#view-details").click(function()
{
var certificateId = $("#view-details").attr('value');
$.ajax({
url: 'get_data.php?id=getCertificateDetails',
type: 'POST',
dataType: 'html',
data: {certificate_id : certificateId},
})
.done(function(resp)
{
var data = $.parseJSON(resp);
if(data.status == 1)
{
var message = "Certificate is Already Issued";
var btn_status = "btn btn-success disabled";
}
else if(data.status == 0)
{
var message = "Click To Confirm Issue!";
var btn_status = "btn btn-danger";
}
else
{
var message = "Technical Issue";
var btn_status = "btn btn-danger disabled";
}
var data = "<div class='modal-dialog'>"+
"<div class='modal-content'>"+
"<div class='modal-header' align='center'>"+
"<h3 class='modal-title'>Certificate Details Are As Follows</h3>"+
"</div>"+
"<div class='modal-body'>"+
"<b>Registration Number</b> : "+data.reg_number+
"<br /><b>Baby's Birth Date</b> : "+data.birth_date+
"<br /><b>Baby's Birth Time</b> : "+data.birth_time+
"<br /><b>Baby's Gender</b> : "+data.gender+
"<br /><b>Baby's Full Name</b> : "+data.baby_name+
"<br /><b>Father's Full Name</b> : "+data.fathers_name+
"<br /><b>Mother's Full Name</b> : "+data.mothers_name+
"<br /><b>Parent's Address While Baby's Birth</b> : "+data.while_baby_birth_parents_address+
"<br /><b>Parent's Permanent Address</b> : "+data.parents_permanent_address+
"<hr /><h4 class='text-center'>Hospital Details</h4>"+
data.hospital_detail+
"<hr /><h4 class='text-center'>Home Details</h4>"+
data.home_detail+
"<hr /><h4 class='text-center'>Other Details</h4>"+
data.other_detail+
"</div>"+
"<div class='modal-footer'>"+
"<button type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button>"+
"<a href='#' class='"+btn_status+"' id='confirm-issue'>"+message+"</a>"+
"</div>"+
"</div>"+
"</div>";
$('#viewDetails').html(data);
$('#viewDetails').modal('show');
})
.fail(function()
{
console.log("error");
});
});
The problem arises when lets take a scenario
have a look at this screenshot
when i click on view details of the very first record the modal is called, but when i click on the next view details the modal doesn't appear. it seems that the modal appears only for the very 1st record present in the table
please can anyone help me with this code
you are generating multiple elements with the same id ("view-details"). That's invalid HTML. Element IDs must be unique. Your click event handler will only work on the first one because it considers that all the later ones are not valid.
Use classes instead (e.g. $( "body" ).on( "click", ".view-details"... instead of $("#view-details").click(... and <div class='btn btn-primary view-details'... as the button (instead of id="view-details")
#view-details id always unique so your modal will only work with first where ever it comes.
For more details about Difference between id and class in CSS and when to use it
so you need to add a class to open model, and some change in your code
HTML :
id='view-details' to <div class='btn btn-primary view-details'>
JS:
$( "body" ).on( "click", ".view-details", function() {
var certificateId = $( this ).attr('value');
// .... Rest of your code here
});
Why Use jQuery .on() because it will bind click handler to every button holding view-details class.
var certificateId = $( this ).attr('value');
Will give you current clicked button's attribute value.

How to pass radio input type value from PHP while loop to HTML?

I have radio button in a PHP while-loop.
I am storing the first row value in the value of radio button.
I need to pass the value of radio button in HTML a href.
How to pass that value with both PHP and HTML in same page??
My code:
index.php
<html>
<body>
<img src="images/print_label.png" name="Image3" width="152" height="110" border="0" align="top" style="margin-top:10px">
<?php
include "db.php";
require_once "purna_insert_orders_to_ship.php";
if(isset($_POST['submit']))
{
if($_POST['value'] == 'readytoship') {
// query to get all Fitzgerald records
$query = "SELECT * FROM orders WHERE status='readytoship'";
}
elseif($_POST['value'] == 'readytodispatch') {
// query to get all Herring records
$query = "SELECT * FROM orders WHERE status='readytodispatch'";
} else {
// query to get all records
$query = "SELECT * FROM orders";
}
$sql = mysql_query($query);
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
echo "<div id='showmenu' class='scroll'>";
echo "<table id='table_struct' cellspacing='0' cellpadding='1' border='1' width='400' height='30'>
<tr class='tr_class' bgcolor='white'>
<td align='center' style='font-weight:bold'> Select </td>
<td align='center' style='font-weight:bold'> Po Id </td>
<td align='center' style='font-weight:bold'> Customer Name </td>
<td align='center' style='font-weight:bold'> quantity </td>
<td align='center' style='font-weight:bold'> price </td>
<td align='center' style='font-weight:bold'> status </td>
</tr>";
while($row = mysql_fetch_array($sql))
{
echo "<tr height='20' data-order_id='".$row['po_id']."'>
<td align='center'><input type='radio' class='case' name='radio' value='".$row['po_id']."'></td>
<td align='center'>".$row['po_id']."</td>
<td align='center'>".$row['customer_name']."</td>
<td align='center'>".$row['quantity']."</td>
<td align='center'>".$row['price']."</td>
<td align='center'>".$row['status']."</td>
";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
}
?>
</body>
</html>
Can anyone please help me out??
To use the value in an anchor tag, you would need to invoke the GET method as follows:
Click here
But, since it is in a radio button, you might want to consider using an HTML form with submit button rather than an anchor tag.
If you want to call that value in html ahref then you should need some jquery too
First you should echo some value in your radio button
<input type="radio" name="buttonval" id="smallBtn" value="yourvalue"/>
Then in the change even of the radio button, You shall fire the event
<script type="text/javascript">
$(document).ready(function()
{
$("input[name=buttonval]").on('change', function(){
var $postID = $('input:radio[name=buttonval]:checked').val();
$postID = "="+$postID;
});
$.ajax ({
type: "GET",
url: "localhost/ajax/buttonvaluereceiver.php",
data: {"postID" : $postID }
});
});
</script>
and in the success event of the ajax call you will get the result of what buttonvaluereceiver.php file does
Update :
As you need to do instantly in radio button change I am updating my answer for you
Here is the html and script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name='frm' id='frm'>
<input type='radio' id='test' value='rad' name='rad'>
</form>
Your link :
<div id='link'></div>
<script>
$("input").change(function(){
var data = $("#frm").serialize();
Call();
});
function Call()
{
$.ajax({
type: "POST",
url : "result.php",
data : $("#frm").serialize(),
success : function(data)
{
console.log(data);
$("#link").html(data);
}
},"json");
}
</script>
Here is the php that creates your link
<?php
echo "<a href='url.php?id".$_POST['rad']."'>Click here</a>";
?>
You can change the url and values according to your need.

Categories