Imagine I have 3 data's in my room_table and the column is room_id, image, room_name then I'm going to display the data of my room_table in my html code.
PS: Ignore the text_checkin, text_checkout first. I'm going to explain after the code.
HTML code:
$db = mysqli_connect('xxxxxx', 'xxxx', '', 'xxxx');
$rooms = mysqli_query($db, "SELECT * FROM rooms ORDER BY id ASC;");
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
<?php while($row = mysqli_fetch_array($rooms)) { ?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" id="text_checkin">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" id="text_checkout">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" id="text_roomid" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg"></p>
</div>
<?php } ?>
I have table named reservation then the columns are room_id, checkin, checkout.
the 3 data's in my room_table will display. Then the textbox, and the button will be thrice cause of the while loop. Then imagine I clicked the button submit in the 2nd row, then the 2nd row id should insert on my table reservation but the problem is only first row id is inserting on table reservation
Here's my script:
<script type="text/javascript">
function chk()
{
var roomid = document.getElementById('text_roomid').value;
var checkin = document.getElementById('text_checkin').value;
var checkout = document.getElementById('text_checkout').value;
var dataString = 'roomid='+ roomid + '&checkin=' + checkin + '&checkout=' + checkout;
$.ajax({
type: "post",
url: "server.php",
data:dataString,
cache:false,
success: function(html){
$('#msg').html("success");
}
});
return false;
}
</script>
PHP code: server.php
$roomid = $_POST['roomid'];
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$query = "INSERT INTO reservation (room_id, checkin, checkout) values ('$roomid', '$checkin', '$checkout')";
mysqli_query($db, $query);
echo "success!";
please help me out of this problem, tyia!
The error lies within your while loop. Your printed elements will all have the same id's. When your function is looking for an id to get the value, it will always return the first that it finds, no matter how many instances there are of that id. So you're having conflicting id's. id's should always be unique.
What you could do to avoid this, is to declare a counter outside your while loop and increment it inside your while loop, then attach that onto your id. In that way, you will always have a unique id to parse along.
For instance:
<?php $count=0; while($row = mysqli_fetch_array($rooms)) { $count++;?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" id="text_checkin<?php echo $count; ?>">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" id="text_checkout<?php echo $count; ?>">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" id="text_roomid<?php echo $count; ?>" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg<?php echo $count; ?>"></p>
</div>
<?php } ?>
However, you will then need to change your logic for how you fetch the data from each element, as you don't really know what their id's could end up being due to the incrementor. It's not static.
If you need any further help, let me know.
As Martin said there is the problem with the id's so you have to change the logic a little bit.
$db = mysqli_connect('xxxxxx', 'xxxx', '', 'xxxx');
$rooms = mysqli_query($db, "SELECT * FROM rooms ORDER BY id ASC;");
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
<?php while($row = mysqli_fetch_array($rooms)) { ?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" class="text_checkin">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" class="text_checkout">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" class="text_roomid" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg"></p>
</div>
<?php } ?>
Then you can get the values individually and pass them as array to the server.
<script type="text/javascript">
function chk()
{
var roomidArr = $(".text_roomid");
var checkinArr = $(".text_checkin");
var checkoutArr = $(".text_checkout");
/*
You can get value of each element as;
for(var i = 0; i < roomidArr.length; i++){
console.log($(roomidArr[i]).val());
}
*/
//var dataString = Apply your logic here as;
$.ajax({
type: "post",
url: "server.php",
data:dataString,
cache:false,
success: function(html){
$('#msg').html("success");
}
});
return false;
}
</script>
Related
I'm trying to make this button checking if Employee ID passing via textbox exsits in Oracle Database and depend on result - show YES or NO after ':'.
But i have absolutely no idea how. I tried to make a form in a form:
<form action="addemp.php" method="POST">
<table>
<tr>
<td>Employee ID: </td>
<td><input type="text" name="empid" size=1/>
<form action="check.php" method="POST">
<input type="submit" name="check" value="Check?"> :
</form>
But no success since It can not be done.
Any suggestions?
EDIT:
check.php
<?php
$conn = oci_connect('hr', 'hr', 'hr');
$stid = oci_parse($conn, "select count(*) from employees where employee_id=TO_NUMBER(".$_GET['idprac'].")");
oci_execute($stid);
$result = oci_num_rows($stid);
// Use this $empId and check in query.
if($result==1){
echo "free";
} else
{
echo "owned";
}
?>
code in index.html
<td><input type="text" name="idprac" size=1/>
<input type="button" name="check" class='checkEmp' value="Check?"> : <span class='showResult'></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('.checkEmp').click(function(){
var empId= $('#idprac').val();
$.ajax({url:"check.php?idprac="+empId,cache:false,success:function(result){
$('.showResult').html(result);
}});
});
</script>
But ajax does not want to pass parameter to check.php (undefined error) and if i set var empID = whatever number gives me always 'owned'.
1) Nested <form> are NOT allowed.
2) To check employee exist or not. Use Ajax.
<form action="addemp.php" method="POST">
<table>
<tr>
<td>Employee ID: </td>
<td>
<input type="text" id='empId' name="empid" size=1/>
<input type="button" name="check" class='checkEmp' value="Check?"> : <span class='showResult'></span>
</td>
</tr>
</table>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('.checkEmp').click(function(){
var empId= $('#empId').val();
$.ajax({url:"check.php?empId="+empId,cache:false,success:function(result){
$('.showResult').html(result);
}});
});
</script>
check.php
<?php
$empId = $_GET['empId'];
// Use this $empId and check in query.
if(employee id is available){
echo "Yes";
} else {
echo "No";
}
?>
I have a table callled tb_app with fields 'id','name','aic','batchcode'
example: field values '1','james','0001','1'
If type james in the textbox(name) corresponding values for other fields(aic,batchcode) should be displayed in textboxes. Is this possible? can anyone help me...I'm a php beginner ...Please!
Form code:
<form method="post">
<input type="text" name="names" id="query" />
<input type="text" name="aic" />
<input type="text" name="batchcode" />
<input type="submit" name="show" />
</form>
You can do this by Jquery ajax Try in this way by using your exact field names it might help you
Your jquery script should be something like this
function getvalues()
{
var selname = $("input[name='names']:text"").val();
$.ajax({ url: "getuserdata.php",
data: {"selname":selname},
type: 'post',
success: function(output) {
$("#aic").val(output);
$("#batchcode").val(output);
}
});
}
and your Html code
<input type="text" name="names" id="query" onblur="getvalues()"/>
<input type="text" name="aic" id="aic"/>
<input type="text" name="batchcode" id="batchcode" />
The getuserdata.php
<?php
include("database connection file here");
$selname = $_POST['selname'];
$query = "SELECT * FROM table_name WHERE youruser_id = $selname";
$res = mysql_query($query);
$rows = mysql_fetch_array($res);
echo $rows['aic'];
echo $rows['batchcode'];
?>
Is there a way, when clicking on a button, using HTML and PHP, to display an alert message containing the name of the session started, a radio button checked and the date and time choose? The button is included in a form, so I am looking if there is way to get these things done...
Here's my code:
<?php
if (!isset($_SESSION)) {
session_start();
}
echo $_SESSION["uname"]; ?>
</div>
<br>
<form id="form1" action="welcome.php" method="post" >
Blood Type Needed :
<br>
<br>
<input id="input1" type="Radio" value="A+" name="bn"/> A
<input id="input1" type="Radio" value="B+" name="bn"/> B
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
$('input[#name="bn"]:checked').val();
var radios = document.getElementsByName('bn');
if (radios.checked) {
function showSession(){
var x=document.getElementById("sessionId");
var y=new Date();
alert(x.value+" wants "+radios.value+y);
}
}
</script>
<input id="done" class="button1" type="button" onClick="showSession();" value=" DONE ">
</form>
I will use a INPUT hidden and a javascript function, after attack it to onClick event on your button, but suggest you use Jquery to make all cross-browser:
HTML input
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
JAVASCRIPT
function showSession(){
var x=document.getElementById("sessionId");
alert(x.value);
}
HTML BUTTON
<input type="button" value="Click me" onClick="showSession();" />
FULL SCRIPT
<?php
if (!isset($_SESSION)) session_start();
echo "Session ID: ".$_SESSION["uname"];
?>
</div><br/>
<script>
function showData(){
var sessionId = document.getElementById("sessionId").value;
var today = new Date();
var x = document.getElementsByName('bn')
var selected = false;
// Check the selected value
for(var k=0;k<x.length;k++)
if(x[k].checked){
alert(' '+ sessionId + " wants " + x[k].value + " " +today);
selected = true;
}
if (!selected) alert('Select something please...');
}
</script>
<form id="form1" action="welcome.php" method="post" ><br/>
Blood Type Needed :<br/><br/>
<input id="AP" type="Radio" value="A+" name="bn"/><label for="AP"> A</label><br/>
<input id="BP" type="Radio" value="B+" name="bn"/><label for="BP"> B</label><br/><br/>
<input id="done" type="button" onClick="showData();" value=" DONE " class="button1">
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
</form>
You can do this by using simple Javascript
<script>
function showValue()
{
var sessionVal=<?php echo $_SESSION['uname']; ?>;
var selectedDate=documnet.form1.dt.value;
var selectedRadio=document.form1.bn.value;
alert(sessionVal+" "+selectedRadio+" "+selectedDate); //what ever format you want to show.
document.form1.actiom='welcome.php';
document.form1.submit();
}
</script>
In your html add onsubmit function
<form id="form1" action="" onsubmit="return showValue();" method="post" >
Ok here is my problem, and all of my 'dirty' code. This isn't my production code but just trying to make it work at the moment.
Basically what I need is when a user selects the Not Ok radio button it displays the textarea for that unique set which it doesn't do right now when I select Not Ok it gives the textarea's for all the entries which right now is about 13 sets of questions that get generated dynamically from a mysql database at the moment. I have a feeling it has to do something with unique id's that are either in the wrong place in my code now, or just simply aren't there at all. Any help is appreciated greatly.
<div data-role="collapsible" data-theme="b" data-content-theme="c">
<h3>Vehicle Check Information</h3>
<?php
$query = mysql_query("SELECT * FROM vehicle_q");
while($row = mysql_fetch_array($query)) {
$q_title = $row['title'];
$q_id = $row['id'];
?>
<div data-role="fieldcontain" style="border:0;">
<fieldset data-role="controlgroup">
<legend><?php echo $q_title; ?>:</legend>
<input type="radio" name="help[]" id="checkbox-1a" value="Ok" />
<label for="checkbox-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-2a" value="Not Ok" />
<label for="checkbox-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?php echo $q_id; ?>" style="display:none;">
<script>
$(document).ready(function(){
$(":radio:eq(1)").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").show(500);
});
$(":radio:eq(0)").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").hide(500);
});
});
</script>
<fieldset data-role="fieldcontain">
<label for="<?php echo $q_title; ?>_t">Explain the Deficiency(If any):</label>
<textarea name="text_a[]" id="<?php echo $q_title; ?>_t"></textarea>
</fieldset>
</div>
</div>
<input type="hidden" name="q_title1[]" value="<?php echo $q_title; ?>" />
<?php
}
?>
</div>
The other 2 answers are ways to fix your issue. As a side, here is possibly why it is happening. When you are using -
$(":radio:eq(1)").click(function()
$(":radio:eq(0)").click(function()
You are using a click listener that just checks for if 'any' radio button with that index position was clicked on your page. So any button with 1 index position will make every $(":radio:eq(1)").click(function() execute.
Edit -
You would want to change your radio button ids, as (1) they will not be unique as you repeat them with each while() loop, and (2) you could use it to check if that specific radio buttton was clicked.
Try changing it to -
...
<input type="radio" name="help[]" id="checkbox-1a-<?php echo $q_id; ?>" value="Ok" />
<label for="checkbox-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-2a-<?php echo $q_id; ?>" value="Not Ok" />
<label for="checkbox-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?php echo $q_id; ?>" style="display:none;">
<script>
$(document).ready(function(){
$("#checkbox-2a-<?php echo $q_id; ?>").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").show(500);
});
$("#checkbox-1a-<?php echo $q_id; ?>").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").hide(500);
});
});
</script>
The easiest way that I have found to show hide elements based off of radio values is to serve up an onchange event based on the id of the element (which you already have). In your case, since you only have two radios based off the same name, the easiest way is a simple if/else statement. Something like:
<script type="text/javascript">
$(function(){
$('#checkbox-1a').change(function(){
if($(this).attr('checked')){
$('#hidden-text-<?php echo $q_id;?>').hide(500);
}else{
$('#hidden-text-<?php echo $q_id;?>').show(500);
}
});
});
</script>
Where we state when #checkbox-1a is changed: if the element is checked (selected), then do something (in your case hide something), otherwise do something else (in your case show something).
Try something like:
<div data-role="collapsible" data-theme="b" data-content-theme="c">
<h3>Vehicle Check Information</h3>
<?php
$query = mysql_query("SELECT id,title FROM vehicle_q");
while($row = mysql_fetch_array($query)) {
$q_title = $row['title'];
$q_id = $row['id'];
?>
<div data-role="fieldcontain" style="border:0;" class="groupings">
<fieldset data-role="controlgroup">
<legend><?=$q_title?>:</legend>
<input type="radio" name="help[]" id="checkbox-<?=$q_id?>-1a" value="Ok" />
<label for="checkbox-<?=$q_id?>-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-<?=$q_id?>-2a" value="Not Ok" />
<label for="checkbox-<?=$q_id?>-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?=$q_id?>" class="hiddenText" style="display:none;">
<fieldset data-role="fieldcontain">
<label for="<?=$q_title?>_t">Explain the Deficiency(If any):</label>
<textarea name="text_<?=$q_id?>_a[]" id="<?=$q_title?>_t"></textarea>
</fieldset>
</div>
</div>
<input type="hidden" name="q_title1[]" value="<?php echo $q_title; ?>" />
<?php
}
?>
</div>
<script>
$(document).ready(function(){
$(".groupings input:radio").click(function(){
if (this.value == "Ok") {
$(this).parent().next('.hiddenText').show(500);
} else {
$(this).parent().next('.hiddenText').hide(500);
}
});
});
</script>
This is untested, but the script only needs to be declared once and it will apply to the rest relative to the radio button.
How do I do unlimited fields in php? Here is the scenario:
At first, there are only 2 fields, lets called: first name1, last name1
What I want to do is, when I click the "add" button, it will add another 2 fields in new row, the fields label/name should be first name2, last name2. And when I click again, it will have first name3, last name3, and so on..
Can anyone give me some sample script in php? I am new to PHP.
The form should be in HTML. If somebody can give Ajax sample code, would be a big plus.
That depends on what you mean by "field." It sounds as though you're talking about a form, which wouldn't be PHP, but instead HTML. You could have a button [Add] post back to the server, which then refreshes the page with another set of form-inputs. You also do that via javascript without having to refresh the page.
Simple Javascript (jQuery) Example:
$(document).ready(function(){
$("input[value='Add']").click(function(event){
event.preventDefault();
$("p.field:last").clone().insertAfter("p.field:last");
});
});
<form method="post">
<p class="field">
<input type="text" name="firstname[]" value="" />
<input type="text" name="lastname[]" value="" />
</p>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
Simple PHP Example:
I don't encourage you use this as-is
<?php
$count = 1;
if ($_POST["submit"] == "Add") {
$count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;
} else
if ($_POST["submit"] == "Done") {
print "<pre>";
print_r($_POST["firstname"]);
print_r($_POST["lastname"]);
print "</pre>";
}
?>
<form method="post">
<?php for($i = 0; $i < $count; $i++) { ?>
<p class="field">
<input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" />
<input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
</p>
<?php } ?>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
There are two ways to do this, either using solely PHP or by some fancy JavaScript. I will tackle the PHP-only solution. A JavaScript solution would be much more responsive as there wouldn't be repeated round trips to the server but it would also only work for users who have JavaScript enabled, whereas a PHP solution works for everybody.
A general outline of the solution is this:
Initially $count is 1, and one row is generated.
If the user clicks Add, the form is posted back to the very same PHP file with a hidden count variable included. The script restarts from the beginning, increments $count, and displays one more row than the last time.
If the user clicks Submit, the names that have been entered are processed.
Here's some sample code. I apologize that I do not have PHP installed on the machine I'm writing this one so this is entirely untested. Hopefully there aren't too many horrendous syntax errors!
<?php
$count = isset($_POST['count']) ? $_POST['count'] : 1;
if (isset($_POST['add']))
++$count;
else if (isset($_POST['submit']))
{
header('Content-Type: text/plain');
print_r($_POST);
exit;
}
?>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
<input type="hidden" name="count" value="<?php echo $count ?>" />
<?php for ($i = 1; $i <= $count; ++$i) { ?>
[<?php echo $i ?>]
First: <input type="text" name="firstName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
Last: <input type="text" name="lastName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
<br />
<?php } ?>
<input type="submit" name="add" value="Add" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Oh and you want a JavaScript solution, eh? Well you've got the really nice jQuery answer already. How about a ridiculously long plain-JavaScript solution, then?
<html>
<head>
<script type="text/javascript">
// <![CDATA[
var count = 0;
function addRow() {
var table = document.getElementById("table");
var row = document.createElement("tr");
var countCell = document.createElement("td");
var countText = document.createTextNode(++count);
var firstCell = document.createElement("td");
var firstInput = document.createElement("input");
var lastCell = document.createElement("td");
var lastInput = document.createElement("input");
firstInput.type = "text";
firstInput.name = "firstName" + count;
lastInput.type = "text";
lastInput.name = "lastName" + count;
table .appendChild(row);
row .appendChild(countCell);
countCell.appendChild(countText);
row .appendChild(firstCell);
firstCell.appendChild(firstInput);
row .appendChild(lastCell);
lastCell .appendChild(lastInput);
}
// ]]>
</script>
</head>
<body>
<form action="somewhere.php" method="post">
<table id="table">
<tr>
<th>Row</th>
<th>First</th>
<th>Last</th>
</tr>
</table>
<script type="text/javascript">
addRow();
</script>
<input type="button" value="Add" onclick="addRow()" />
<input type="submit" value="Submit" />
</form>
</body>
</html>