I'm setting up a dynamic webpage that will be used as a time stamp for employes. After you log in, you will write down when you started work, how long the break was, when you finished and so on..
Problem is that every time I wanna change something on the webpage, for example I want to change my break time, it won't change and shows me the user_id instead.
I'm still a beginner when it comes to PHP and don't know where the problem is..here are some code snippets
<div class="header">
<ul>
<li>
<p class="text">HourBook</p>
</li>
</ul>
</div>
<table class="table table-striped table-bordered">
<tr>
<th class="luecke1">Name</th>
<th class="luecke2">Start Time</th>
<th class="luecke3">Pause</th>
<th class="luecke4">End Time</th>
<th class="luecke5">Comments</th>
<th class="luecke6">Duration</th>
</tr>
<?php
$connect = new mysqli('localhost', 'root', '', 'hourbook');
$result = $connect->query("SELECT * FROM data");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
echo "<tr>";
echo "<td class='luecke1'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['user_id'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\"})'></input></td>";
echo "<td class='luecke2'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['start_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"start_time\"})'></input></td>";
echo "<td class='luecke3'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['pause_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"pause_time\"})'></input></td>";
echo "<td class='luecke4'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['end_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"end_time\"})'></input></td>";
echo "<td class='luecke5'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['comments'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"comments\"})'></input></td>";
echo "<td class='luecke6'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['total_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"total_time\"})'></input></td>";
}
} else {
echo "No results!";
}
?>
<script>
var oldValue;
function pruefung(params) {
var newValue = document.getElementById('editor' + params.currentid).value; //editor id verknüpfung falsch?
if (oldValue == newValue) {
console.log("no changes");
} else {
console.log("changes");
$.ajax({
url: "update.php",
type: "POST",
data: {
value: newValue,
id: params.currentid,
fieldname: params.currentfieldname
},
success: function(data) {
alert("Saved successfully!");
document.location.reload(true);
},
error: function(data) {
alert("error: " + data);
}
})
}
}
</script>
</table>
In your AJAX call you have : var newValue = document.getElementById('editor' + params.currentid).value;
In your table, for each row you have : id='editor" . $id . "'. This is a duplicate of ids.
When doing var newValue = document.getElementById('editor' + params.currentid).value; You are getting the first element that has this id, that's why newValue is always the id (the first row holding the id value)
I suggest you to remove that var newValue = ... but instead insert the value in the object you pass as parameter of pruefung(), such as onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\",value:\"" . $row['user_id'] . "\"}) for the id row, onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\",value:\"" . $row['start_time'] . "\"}) for the start time row, and so on...
And then, in your AJAX call, replace var newValue = document.getElementById(...) by var newValue = params.value
Related
I need to exicute one JS function after another sequencually. I can exicute these functions individually and they work but when I put them in a sequence I only get the openPatient() and the openMessage() does not exicute. My JS functions
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
My function call:
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
This function call exists in this process:
<?php
// Generate a table row for each pending portal request or message.
// This logic merges requests with messages by date.
$v1 = each($result['list']);
$v2 = each($result['messages']);
while ($v1 || $v2) {
echo " <tr class='detail' bgcolor='#ddddff'>\n";
if (!$v2 || $v1 && $v1[1]['datetime'] < $v2[1]['datetime']) {
$postid = $v1[1]['postid'];
$ptname = patientNameFromLogin($v1[1]['user']);
// Get the portal request data.
if (!$postid) die(xlt('Request ID is missing!'));
$result2 = cms_portal_call(array('action' => 'getpost', 'postid' => $postid));
if ($result2['errmsg']) {
die(text($result2['errmsg']));
}
// Look up the patient in OpenEMR.
$ptid = lookup_openemr_patient($result2['post']['user']);
echo " <td>" . text($v1[1]['user']) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;' onclick=\"openPatient()\">" .text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
echo " <td>" . text($v1[1]['type' ]) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_req_cb[" .
attr($postid) . "]' value='" . attr($postid) . "' /></td>\n";
$v1 = each($result['list']);
}
else {
$messageid = $v2[1]['messageid'];
$ptname = patientNameFromLogin($v2[1]['user']);
echo " <td>" . text($v2[1]['user']) . "</td>\n";
echo " <td>" . text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openMessage(" .
"'" . addslashes($messageid) . "'" .
")\">" . text($v2[1]['datetime']) . "</td>\n";
echo " <td>" . text($v2[1]['user'] == $v2[1]['fromuser'] ?
xl('Message from patient') : xl('Message to patient')) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_msg_cb[" .
attr($messageid) . "]' value='" . attr($messageid) . "' /></td>\n";
$v2 = each($result['messages']);
}
echo " </tr>\n";
}
?>
I am thinking part of the problem may be that openPatient() opens in another window. Perhaps it is loosing focus. Any tips to fix this would be appreciated.
EDIT:
What I have tried and helps is adding return this; to openPatient():
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
This then executes the next function but the next function executes too soon. it needs to wait for openPatient() to fully load before executing openMessage(). I have tried adding setTimeout( wait, 1000 ); but then openMessage() does not execute at all.
The solution:
The call:
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient();setTimeout(function(){openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
")}, 2500);\">" . text($v1[1]['datetime']) . "</td>\n";
The functions:
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
Keys to success: return this; and the use of the anonymous function with setTimeout in the call.
Posts that helped:
What does "return this" do within a javascript function?
setTimeout delay not working
I have this script which is triggered when a button with the class .press_me is pressed.The buttons are on a column from a php generated mysql table:
$result = mysqli_query($con,"SELECT * FROM tbname");
echo "<table id='main'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='right-middle user'>" . $row['ID'] . "</td>";
echo "<td class='right-middle user'>" . $row['Nume'] . "</td>";
echo "<td class='right-middle done'>" . $row['Teme_facute'] . "</td>";
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me'>" ."</td>";
echo "<td class='right-middle undone'>" . $row['Teme_nefacute'] . "</td>";
echo "<td class='right-middle uncheck'>" . "<img src='img/uncheck.png'>" . "</td>";
echo "<td class='side-table resetDone'>" . "<img src='img/resetDone.png'>" . "</td>";
echo "<td class='side-table resetUndone'>" . "<img src='img/resetUndone.png'>" . "</td>";
echo "</tr>";
}
echo "</table>";
And the script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
And counter.php:
<?php
echo $_POST["id"];
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
I'm having trouble updating only the value on the same row as the button pressed.When i run the page in this configuration counter.php returns no id passed and i think the problem is with the passing of the row id. Can anyone help me update only the value on the row with the pressed button?
I'm aware of sql injection but it's not the main problem now
Your id is empty
try this
echo "<td class='right-middle check'>" . "<img data-id='{$row['ID']}' src='img/check.png' class='press_me'>" ."</td>";
And in the script use this
var id=$(this).data("id");
change you javascript, looks like you are not sending data at all
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php",
// add this line
data: { id: id}
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
Replace below script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo $row[ID]; ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
NOTE: I assume that you are working with single record. If not then it
will going wrong.
If this is working wrong then replace .press_me line with below:
$id = $row['ID'];
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me' id='<?php print($id);?>' >" ."</td>";
And script is like:
var id = $(this).attr("id");
Hope this help you well!
i am searching for a way to pass variable ($result[1]) to a session variable from while loop within a link. will be glad for some help
while ($result = mysqli_fetch_array($dataset,MYSQLI_NUM)){
echo "<tr>";
echo " <td >", "<a href='Rate_Supplier.php'>" . $result[1] ."
</a>","</td>" ;
echo " <td >" . $result[0] . "</td>" ;
echo " <td >" . $result[2] . "</td>" ;
echo "</tr>\n";
}
Have been searching around for a while and can't find a proper answer to this problem. I have a "finance" tracker that has several hidden divs which using jQuery appear when the button to show that div is clicked. I have a Asset Tracker which queries a database and upon being checked updates the database with new values in adjacent input rows where the checkbox is located. I am trying to get the checkbox to submit the data without causing the page to reload and the div to "toggle" off again.
On the form section I attempted to remove the method='post' but instead when checking the box it reloaded the page and added all the post variables to the URL string. I removed the action='FBook.php' in an attempt to prevent the reloading, but that did not resolve the problem.
Here is the related code from the PHP file:
if(isset($_POST['AssetSetUpdate'])) { $AssetLastUpdate = $dtNowDate->format('Y-m-d');
foreach($_POST['AssetID'] as $key => $id) { if(isset($_POST['AssetSetUpdate'][$key])) {
$stmt_ATrackUp -> bindParam(':UpDate', $AssetLastUpdate, PDO::PARAM_STR, 10);
$stmt_ATrackUp -> bindParam(':UpNotes', $_POST['AssetNotes'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpThis', $_POST['AssetDescription'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpVal', $_POST['AssetValue'][$key], PDO::PARAM_INT, 3);
$stmt_ATrackUp -> execute(); } else continue; }
echo "<div class='Notice'>" . $PageTitle . " / Assets updated!</div>"; }
(other code)
$(document).ready(function() {
$("#AssetUpdateForm").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'FBook.php',
data: $(this).serialize(),
success: function() { alert('form submitted'); },
});
return false;
});
$('#ShFBAsset').click(function() { $('#FBAsset').toggle('slow'); });
(other code)
});
(other code)
$AssetCounter = 1;
$stmt_ATrack -> execute(); while ($row_ATrack = $stmt_ATrack -> fetch(PDO::FETCH_ASSOC))
{
$ChAge = $row_ATrack['Checked']; $cChAge = ''; switch(true)
{
case (strtotime($ChAge) >= strtotime('-7 days')): $cChAge = 'FBCAN'; break;
case (strtotime($ChAge) >= strtotime('-30 days')): $cChAge = 'FBCA1'; break;
case (strtotime($ChAge) >= strtotime('-90 days')): $cChAge = 'FBCA3'; break;
default: $cChAge = 'FBCA6'; break;
}
if(isset($row_ATrack['Serial'])) { $IfDSerial = "<strong>Serial: </strong>" . $row_ATrack['Serial'] . "<br/>"; } else { $IfDSerial = ''; }
if(isset($row_ATrack['UPC'])) { $IfDUPC = "<strong>UPC: </strong>" . $row_ATrack['UPC'] . "<br/>"; } else { $IfDUPC = ''; }
if(isset($row_ATrack['Related'])) { $IfDRelated = "<strong>Related: </strong>" . $row_ATrack['Related'] . "<br/>"; } else { $IfDRelated = ''; }
if(isset($row_ATrack['Location'])) { $IfDLocation = "<strong>Location: </strong>" . $row_ATrack['Location'] . "<br/>"; } else { $IfDLocation = ''; }
if(isset($row_ATrack['TagPhoto'])) { $IfDTagPhoto = "<strong>Tag photo: </strong><a href='Images/INV/" . $row_ATrack['TagPhoto'] . ".JPG'>" . $row_ATrack['TagPhoto'] . "</a><br/>"; } else { $IfDTagPhoto = ''; }
$IfDetails = "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'>" . ($IfDSerial) . ($IfDUPC) . ($IfDRelated) . ($IfDLocation) . ($IfDTagPhoto) . "</div></div>";
if($IfDetails == "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'></div></div>") { $IfDetails = ''; }
echo "<form id='AssetUpdateForm[" . $AssetCounter . "]' method='post'>";
echo "<tr><input type='hidden' name='AssetID[" . $AssetCounter . "]' value='" . $AssetCounter . "' />";
echo "<td><input type='hidden' name='AssetDescription[" . $AssetCounter . "]' value='" . $row_ATrack['Description'] . "' /><a href='https://www.google.com/#q=eBay+" . $row_ATrack['Description'] . "' target='_new_AssetSearch'>" . $row_ATrack['Description'] . "</a></td>";
echo "<td>" . $row_ATrack['Type'] . " - " . $row_ATrack['Category'] . "</td>";
echo "<td><input type='checkbox' name='AssetSetUpdate[" . $AssetCounter . "]' value='Now' onchange='this.form.submit();' /></td>";
echo "<td><input type='number' name='AssetValue[" . $AssetCounter . "]' value = '" . $row_ATrack['Value'] . "' style='width: 75px;' /></td>";
echo "<td class='" . $cChAge . "'>" . $ChAge . "</td>";
echo "<td><input type='text' name='AssetNotes[" . $AssetCounter . "]' value = '" . $row_ATrack['Notes'] . "' style='width: 140px;' /></td>";
echo "<td>" . $IfDetails . "</td>";
echo "</tr>";
echo "</form>";
$AssetCounter++;
}
Your JavaScript:
$("#AssetUpdateForm")
… is working on a form with id="AssetUpdateForm".
Your PHP says:
id='AssetUpdateForm[" . $AssetCounter . "]'
which in HTML terms becomes:
id='AssetUpdateForm[something]'
Even if the variable is empty, you still have the square brackets, so the ID is not going to match and the JavaScript event handler will never be bound to that element.
You need to either use the real ID or, since it appears that it can change, add a class to the form and use a .class-selector in the JavaScript.
NB: Your HTML is invalid. The particular problem you have has the potential to cause the same symptoms are you describe so just fixing the problem above might not be enough. Use a validator and write valid HTML too.
Had nothing to do with the HTML or PHP. Turns out that jQuery AJAX was conflicting with the onclick='this.form.submit();' property. I removed that and changed the ajax request to the following - and while it still has bugs as it won't work on the 2nd ajax request, it validates everything else is fine.
$(".Check2Update").on('change', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'FBook.php',
data: $(this.form).serialize(),
success: function(html) {
console.log('Successfully submitted AJAX!');
$("#TableAssets").replaceWith($('#TableAssets', $(html)));
}
});
});
hope you can help
I want to have a drop down list that searches my mysql database and shows the first and last names of the users. You can then select any of the names and it will generate the rest of the membership details (i.e. date signed up, last logged in etc).
I have got the dropdown list working fine, but my problem comes with the next step of generating the rest of the details. With my below code it just shows the details of the last user who signed up and does not change when I change the name in the drop down menu.
I'm pretty sure I need Javascript to help get this working but as I am a beginner to PHP/MYSQL any advise toward the right direction for me would be great. Thanks
This is the code which searches my database and puts the first and last name in to a drop down list
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
echo '<select name="name" style="width: 400px">';
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option>' . $firstname . " " . $lastname . '</option>';
}
echo '</select> <p>';
Again the above code works fine, but the below code is what I am having difficulty with
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
if you don't want to use AJAX to dynamically load the content, you need a form to submit the data, your problem is that after your first loop, $firstname is the last user loaded into the , to make your code work, you need a form.
just put the select in a form and add a button
<form action="mypage.php" method="get">
<select name="name" style="width: 400px">
<?php
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option>' . $firstname . " " . $lastname . '</option>';
}
?>
</select>
<input type="submit" value="Load User Data">
</form>
then in mypage.php you need to check if the form is submitted, and show the user details.
<?php
if(isset($_GET["name"])) {
//this form is posted, show user details
//$firstname = $_GET["name"]; <--- SQL Injection enabled here!!
$firstname = mysqli_real_escape_string($_GET["name"]); // please try to avoid SQL injection!
//your code continues here
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
}
last note, if you don't want the username to appear in the querystring, change form action to post, and get variable using $_POST["name"]
EDIT: if you want the form to autopost using javascript then add this to ur select definition:
<select name="name" style="width: 400px" onchange="this.form.submit()">
but bear in mind that a lot of users block javascript, thus this will not work.
The best way would be to use AJAX to get the data of the other script. However, another (far less elegant and efficient) way of doing it is while you're looping through the names to put into the select. You can also be using the names to get the info for that name and put it into an array (but don't echo it) until you need it.
Use this code from where user will select the name
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js">
<script type="text/javascript">
$(document).ready(function()
{
$(".listdata").change(function()
{
var dataString = 'listdata='+ $(this).val();
$.ajax
({
type: "POST",
url: "alldata",
data: dataString,
cache: false,
success: function(html)
{
$(".alldata").html(html);
}
});
});
});
</script>
<?php
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
echo '<select name="name" style="width: 400px" class="listdata">';
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option value="'.$firstname.'">' . $firstname . " " . $lastname . '</option>';
}
echo '</select> <p>';
?>
<div class="alldata">
<!--here your all data will come-->
</div>
<br/><br/>
Crate one more and give the name alldata.php
And use the below code on that page
<?php
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
?>
Just to complete your options, here you have a full but basic AJAX implementation (using jQuery):
File select.php (javascript part at the bottom of the file):
<?php
// Notice that you'll need to get the $dbc from somewhere, maybe require 'db.php'?
// Retrieve list of people... (notice I've added id column!)
$sql = "SELECT id, first_name, last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
$people = [];
while ($row = mysqli_fetch_assoc($query)){
$people[$row['id']] = $row['first_name'] . " " . $row['last_name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>List of people</title>
<style type="text/css">
.error {
color: red;
box-shadow: 0px 0px 15px 0px rgba(247, 17, 40, 0.44);
}
#person-info {
padding: 10px;
margin-top: 1em;
}
</style>
</head>
<body>
<h2>People list</h2>
<label for="person">Please select one person</label>
<select name="person" id="people-selection">
<option value="-1"></option>
<?php foreach ($people as $person_id => $person_name): ?>
<option value="<?php echo $person_id ?>"><?php echo $person_name ?></option>
<?php endforeach; ?>
</select>
<div id="person-info"><!-- here we will put person info using AJAX request --></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("#people-selection").on('change', function(e) {
if ($(this).val() != -1) { // If we did select some value
$.ajax({
type: "POST",
url : "/get_people_info.php",
data: { id: $(this).val() },
})
.done(function(data) {
$("#person-info")
.removeClass("error") // we don't need the error class here, it's a success response
.html(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$("#person-info")
.addClass("error") // in order to add some UI for the user
.html("Something went wrong!<br><blockquote>" + errorThrown + "</blockquote>");
});
}
else {
$("#person-info")
.removeClass("error")
.html("");
}
})
});
</script>
</body>
</html>
And then get_people_info.php
<?php
if ($_SERVER['REQUEST_METHOD'] !== "POST") {
header('HTTP/1.0 400 Bad request');
die("Only POST request accedpted!");
}
if (!isset($_POST['id'])) {
header('HTTP/1.0 400 Bad request');
die("id parameter is mandatory!");
}
$id = (int) $_POST['id'];
// Notice that you'll need to get the $dbc from somewhere, maybe require 'db.php'?
$sql = "SELECT * FROM registration_tbl WHERE id = ". $id .";";
$query = mysqli_query($dbc, $sql);
if ($row = mysqli_fetch_array($query)){
echo "<p>ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "</p>";
}
else {
echo "Person not found!";
}
Let me give you some further reading (you said you were new to PHP, I asume the whole web development):
jQuery Learning center
PHP: The right way