I've a link in admin-dashboard page which on click shows "doctor-details". Now I want the admin must be able to click on the options link in the table and see full details of the doctor in the same page(I'll probably use modals for this).
So my question is how do I get the ID from the table and send it to another php file for database query?
my code for generating details about doctor(doctor-details.php)
<?php
require('config.php');
$sql = "SELECT * FROM doctor";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0){
while($rows = mysqli_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['id'];?> </td>
<td><?php echo $rows['f_name'];?></td>
<td><?php echo $rows['l_name'];?></td>
<td><?php echo $rows['email'];?></td>
<td><?php echo $rows['contact_number'];?></td>
<td><?php echo $rows['gender'];?></td>
<td> Options</td>
</tr>
<?php
}
}
?>
and finally my ajax:
$(document).ready(function(){
$("#load-doctor-data").click(function(){
$.ajax({
url: 'views/admin/doctor-details.php',
type: 'POST',
success: function(result){
$("#response-doctor").html(result);
}
});
});
});
//Hide table on login
$("#show-doctor-details").hide();
$(document).ready(function(){
$("#load-doctor-data").click(function(){
$("#show-doctor-details").show();
$("#show-patient-details").hide();
});
});
So, the gist is I want to click on options and show full details of John Doe.
Data attributes are a pretty easy to pass data. So when first appending make sure you have the id in the options field like this:
<td> Options</td>
Now you can get this id in your click event handler like this:
$(document).on('click','.options', function(){
var currentId = $(this).data('id');
...
});
Also you don't need two document readys. You can wrap both event handlers in one document ready.
Related
I need a little help for my ajax request. I think i don't get the good value but i have tried more methods, without success.
The purpose is when we click on Info client, another array is displayed with more info. But I always have the last id added and not the id's clicked's row.
My HTML :
<div>
<table id="list_client" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
require 'config.php';
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client) : ?>
<tr id="<?php echo $client["id_client"]; ?>">
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client']; ?>);">Info client</button></td>
<td><button type="button" onclick="hide_info(<?php echo $client['id_client']; ?>);">Masquer client</button></td>
<?php endforeach; ?>
</table>
</div>
My JavaScript and Ajax request:
function display_info() {
$("#info").click(function () {
var datas = {
action: "read",
id_client: $("#id_client").val(),
};
$.ajax({
type: "GET",
url: "function.php",
async: true,
data: datas,
dataType: "json",
cache: false,
}).done(function (result) {
console.log("result");
$("#result").text("response : " + JSON.stringify($result));
});
});
}
#result is a div besides the array. (to test)
My PHP function :
function read() {
global $db;
$id_client = $_GET['id_client'];
$client = "SELECT * FROM client WHERE id_client = '$id_client'";
$query = $db->prepare($client);
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch();
echo json_encode($result);
}
I think I am close but no idea what I did wrong.
Issues:
#1 <tr id="<?php echo $client["id_client"]; ?>">
In the above code, how will you dynamically get the id of the client when trying to use it in Javascript?
#2 <td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client']; ?>);">Info client</button></td>
Above code will make all buttons have same id which is info. id needs to unique per HTML element.
#3 id_client: $("#id_client").val(),.
There is no element with id as id_client.
#4 function display_info() { $("#info").click(function () {.
You are attaching an onclick as well as a click event listener which is not required. Do either of them and not both but I would recommend the latter one.
#5 $client = "SELECT * FROM client WHERE id_client = '$id_client'";
You aren't preparing the query here with a placeholder but rather just adding the retrieved id in the query which is very unsafe since we can't trust user input.
#6 You also missed a closing tr tag.
Solution:
For issue #1, no need to attach an id attribute to a tr tag at all.
For issue #2, make info a class name instead of the id and remove onclick as it isn't needed.
For issue #3, we would get the id_client value from the data-id attribute which we will attach to the respective info button.
For issue #4, encapsulating click event listener inside display_info is not needed. We can directly attach the listener.
For issue #5, we will add a placeholder for id_client to properly bind our primitive value inside the query.
For issue #6, we will add a closing tr tag.
Snippets:
Frontend:
<div>
<table id="list_client" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
require 'config.php';
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client):
?>
<tr>
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="info">Info client</button></td>
<td><button type="button" class="hide_client" data-id="<?php echo $client["id_client"]; ?>">Masquer client</button></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<script>
$(".info").click(function(){
var datas = {
action: "read",
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: datas,
dataType: "json",
cache: false,
}).done(function(result) {
console.log("result");
$("#result").text("response : " + JSON.stringify($result));
});
});
$('.hide_client').click(function(){
let client_id = $(this).attr('data-id');
// do your thing here
});
</script>
Backend:
<?php
function read() {
global $db;
$id_client = $_GET['id_client'];
$query = $db->prepare("SELECT * FROM client WHERE id_client = :id_client");
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch();
echo json_encode($result);
}
Not sure if that's the error you're having, but
$client = "SELECT * FROM client WHERE id_client = '$id_client'";
should probably read
$client = "SELECT * FROM client WHERE id_client = :id_client";
as the binding of the prepared statement doesn't work otherwise.
Other than that: Can you check which results you get from your select query and if that's the result you expect?
you are giving the clientid over to the function display_info, you don't need to read it out with jquery... just change
function display_info() {
to
function display_info(clientid) {
and change the
var datas = {
action: "read",
id_client: $("#id_client").val(),
};
to
var datas = {
action: "read",
id_client: clientid,
};
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
So I've this admin-dashboard where I want to click on the options link which will take me to another page or show a modal of that particular person's details.
So basically, I want to get the ID of one particular person and send it to backend for query and display the details.
My doctor-details.php file
<?php
require('config.php');
$sql = "SELECT * FROM doctor";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0){
while($rows = mysqli_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['id'];?> </td>
<td><?php echo $rows['f_name'];?></td>
<td><?php echo $rows['l_name'];?></td>
<td><?php echo $rows['email'];?></td>
<td><?php echo $rows['contact_number'];?></td>
<td><?php echo $rows['gender'];?></td>
<td> Options</td>
</tr>
<?php
}
}
?>
my ajax code for doctor's details
//For Doctor
$(document).ready(function(){
$("#load-doctor-data").click(function(){
$.ajax({
url: 'views/admin/doctor-details.php',
type: 'POST',
success: function(result){
$("#response-doctor").html(result);
}
});
});
});
//Hide table on login
$("#show-doctor-details").hide();
$(document).ready(function(){
$("#load-doctor-data").click(function(){
$("#show-doctor-details").show();
$("#show-patient-details").hide();
});
});
window.addEventListener('load', function() {
var trs = document.getElementById('response-doctor').querySelectorAll('tr');
for (var i = 0; i < trs.length; i++) {
var tds = trs[i].querySelectorAll('td');
tds[tds.length-1].querySelector('a').setAttribute('href', '/user/'+tds[0].innerHTML);
}
});
My bad, this sloution more easier (inside doctor-details.php):
<td> Options</td>
You can make entire table row as link
For example:
<tr a="profile.php?id=<?php echo $rows['id'?];">
...
<tr>
This is how you can add link on every row which leads you to profile.php file where you can show personal information. When you are in profile.php you can access person's id with $_GET['id'] and fetch data from database using this id. If you are looking for more detailed answer don't hesitate to ask.
I'm attempting to create a shipping status page and I want a really basic feature to work. I want to be able to press a button on this page that says "Mark Shipped". Then I want the button's text to change to "Shipped". I then want the option to change the status of that back to "Mark Shipped', but have an alert prevent it from doing it until you click Proceed or something like that.
I am attempting to do this with php and ajax. I've never used Ajax before or too much JS, so I'm not too sure on how to use the two simultaneously.
I have created a database table that will house the status of the 'shipped' status, so whenever I click the 'mark as shipped' button the word 'shipped' will go into my db table with the id of the order and then I want the word shipped to echo back into that button and remain there indefinitely. The php query was working great until I changed the action of the Ajax script.
So this is my table...
if( $result ){
while($row = mysqli_fetch_assoc($result)) :
?>
<form method="POST" action="shippingStatus.php">
<tr>
<td class="tdproduct"><?php echo $row['order_id']; ?> </td>
<td class="tdproduct"><?php echo $row['date_ordered']; ?> </td>
<td class="tdproduct"><?php echo $row['customer_name']; ?> </td>
<td class="tdproduct"><?php echo $row['streetline1'] . "<br />" . $row['streetline2'] . "<br />" . $row['city'] . ", " . $row['state'] . " " . $row['zipcode']; ?> </td>
<td class="tdproduct"><?php echo $row['product_name']; ?> </td>
<td class="tdproduct"><button data-text-swap="Shipped">Mark Shipped</button></td>
<input type="hidden" name="product_id" value="<? echo $row['id']; ?>"/>
<td class="tdproduct"><input name="delete" type="submit" value="DELETE "/></td>
</tr>
</form>
<?php
endwhile;
}
?>
</table>
This is my Ajax script. At first I had 'shipped' as the action, but it wasn't saving the status. When I would reload the page it would go back to 'Mark Shipped'.
<script>
$("button").on("click", function(e) {
e.preventDefault()
var el = $(this);
$.ajax({
url: "shippingStatusSend.php",
data: {action: "<?php echo $shipped; ?>", order: order_id},
type: "POST",
dataType: "text"
}).fail(function(e,t,m){
console.log(e,t,m);
}).done(function(r){
//Do your code for changing the button here.
//Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
el.text() == el.data("text-swap")
? el.text(el.data("text-original"))
: el.text(el.data("text-swap"));
});
});
</script>
My php in a page called shippingStatusSend:
<?php
//connection to db
$con = mysqli_connect("localhost", "root", "", "bfb");
//Check for errors
if (mysqli_connect_errno()) {
printf ("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$order_id = trim($_POST['order_id'] );
$status = trim($_POST['action'] );
$shipped = "Shipped";
$markshipped = "Mark Shipped";
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "INSERT INTO shippingStatus (order_id, status, date_Shipped) VALUES (?, ?, NOW())")) {
/* bind parameters for markers */
$stmt->bind_param('is', $order_id, $status);
/* execute query */
$stmt->execute();
echo $shipped;
/* close statement */
mysqli_stmt_close($stmt);
}
while($row = mysqli_fetch_assoc($stmt)){
$shipped = $row['status'];
$markshipped = "Mark Shipped";
}
else
echo $markshipped;
?>
I am not sure what I am doing wrong, could anyone point me in the direction of what is wrong? Is it my php code or the way I'm attempting to do this with Ajax or both. Which area of my code is wrong?
Problem: All the other portions of the program works. When I add data:$("#friendadd").val() it won't update the table. I believe the problem might be with the value form? I've seen others use it to get the value of textboxes but shouldn't it still work when using a submit button?
Purpose: each user on the website has an add-as-friend button next to it. When you click on that button, I want to put the userid of that user into a database "friends".
Javascript
<script>
$(document).ready(function(){
$("#friendadd").submit(function(){//Used to be .each
$.ajax({
type:"POST",
url:"getuser.php",
data:$("#friendadd").val()
});//Add data: and success:function
//$.post('getuser.php');//JSON AJAX, {UserId:"13", FriendId:"16"}
})
});
</script>
PHP and HTML; $ctk_values are each of the users
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" value="<?php echo $ctk_values[$i][4];?>"><br>
<?php
}//Ends for loop
?>
</form>
<?php
}
}
?>
getuser.php
<?php
if(!isset($_SESSION)){
session_start();
}
require "conn.php";
$gtu = $dbh->prepare("INSERT INTO friends (AskerId, AcceptorId, mutual, type) VALUES(:AskerId, :AcceptorId, :mutual, :type)");
$gtu->execute(array(
'AskerId'=>$_SESSION['UserId'],
'AcceptorId'=>$_POST['friendadd'],
'mutual'=>false,
'type'=>'friend'
));
?>
I am new to jquery I know it is just a simple method to creating a function in jquery. but I am having a error in my code if anyone can help me I shall be very thankful to him.
What I have:
I have a table. in front of every record there are two buttons one for edit and one for delete record.
What I am trying to do:
When I click button it have to direct me to other page with record id where I have my PHP query to manipulate my database record.
This is how my table looks like:
This is my html code:
<tr id="<?php echo $row['id']; ?>">
<td><?php echo $inc; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['father_name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['contact']; ?></td>
<td>
<?php echo "<button class='btn' value='".$row['id']."' onclick='update(this.value)'>Edit</button>" ?>
</td>
<td>
<?php echo "<button class='btn' value='".$row['id']."' onclick='delete(this.value)'>delete</button>" ?>
</td>
</tr>
This is my Jquery code:
function delete(str){
$('delete.php?q='+str);
}
I know something is wrong but I don't know what I will also appreciate suggestion to learn.
Use ajax request for that.
function delete(value){
$.ajax({
data:{'q':value},
type:'POST',
url:'delele.php',
success:function(xhr){
console.log("record delelte");
}
});
}
Use window.location.href to redirect the page
function delete(str){
window.location.href = 'delete.php?q='+ str ;
}
Jquery try this:
$(function() {
$(document).on("click", ".btn" , function() {
var rowId = this.value;
window.location = 'delete.php?q='+ rowId ;
});
});
jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
It is better than using window.location.href =, because replace() does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";