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,
};
Related
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.
I have a table that it's content is comes from database.When I click on the delete button I want to delete that row with Ajax. Actually right now it's working but with a bug and that is all of the rows get deleted when I click on the button and then if I refresh , the row that I was deleted is gone and other rows are shown.But as I said it needs a refresh.Any solution would be appreciated .
$('.dashboard-subscribe-form').submit(() => {
event.preventDefault();
const currentHiddBtn = $('.dash-subscribe-form-btn');
console.log(currentHiddBtn.closest('tr'));
const userCaution = confirm('Want to delete this quote?');
if (userCaution) { //If admin insists to delete the row
const deleteId = $('.dash-subscribe-form-btn').attr('value');
$.ajax({
type: "POST",
url: "delete-subscribe.php",
dataType: "json",
data: {
deleteId: deleteId
},
success: (data) => {
if (data.code === '200') {
console.log('It works!');
currentHiddBtn.closest('tr').css('background', 'tomato');
currentHiddBtn.closest('tr').fadeOut(1200, () => {
});
} else if (data.code === '404') {
alert('An error occurred!Please try again.');
}
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tbody>
<?php
$count = 1;
$sqlCommand = "SELECT * FROM `kq0b3_subscribe`";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$sqlCommandPrepare->execute();
while ($result = $sqlCommandPrepare->fetch()) {
?>
<tr id="row-<?php echo $result['id']; ?>">
<td class="dashboard-records">
<?php echo $count; ?>
</td>
<td class="dashboard-records">
<?php echo $result['email']; ?>
</td>
<td>
<form action="" method="post" class="dashboard-subscribe-form">
<input id="<?php echo $result['id']; ?>" type="hidden" class="dash-subscribe-form-btn" name="hidden-del" value='<?php echo $result[' id ']; ?>'/>
<button type="submit" name="sub-del-btn" class="btn btn-danger del" value='<?php echo $result[' id ']; ?>'> Delete
</button>
</form>
</td>
</tr>
<?php
$count++;
}
?>
</tbody>
delete-subscribe.php:
<?php
require_once('config.php');
$delete_row = $_POST['deleteId'];
if($delete_row){
$sqlCommand = "DELETE FROM `kq0b3_subscribe` WHERE `id` = ?";
$sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
$result = $sqlCommandPrepare->execute([
$delete_row
]);
/*The json_encode() must be after all of our calculation codes and DB query codes and...(It must be the
last line of code) */
echo json_encode(['code' => '200'], JSON_THROW_ON_ERROR, 512);
}
else {
echo json_encode(['code' => '404'], JSON_THROW_ON_ERROR, 512);
}
UPDATE2: now I'm using :
$('#row-' + deleteId).css('background', 'tomato');
$('#row-' + deleteId).fadeOut(1200, () => {
});
but the new problem is : it doesn't matter which button I click, the forst row is deleted (when any button is clicked , in the console , the id of the first row-button is printed , not the actual id that I was clicked. ).How can I fix this one?
I think the main issue, in this case, is using CSS classes as a selector and it seems to be selecting the first instance no matter which item you are clicking.
The code causing this is:
const deleteId = $('.dash-subscribe-form-btn').attr('value');
You want to be getting the target input from the event object passed from your .submit().
I have created a jsfiddle with an example that could be adapted to your code but here is a quick preview of jQuery part.
$('.dashboard-subscribe-form').submit((event) => {
event.preventDefault()
console.log(event.target.elements[0]["value"])
$('#result-from-click').html("Input Value: " + event.target.elements[0]["value"])
})
It is selecting the first element within the elements array which is the input. If you want the button you can use event.target.elements[1]
You could then also use the value returned to remove the <tr> with the same id instead of finding the nearest. This could be done in the success part of your ajax call without doing a refresh.
I want to send id of element to php and create session for this.
This is piece from php file:
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['p_id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php
}
?>
And in this file javascript code:
$(document).on('click', '.open_item', function(event){
var data_item = this.getAttribute("data-id");
$.ajax({
url: 'get_id.php',
type: 'POST',
data-type: 'json',
data: { id: data_item },
contentType: 'application/x-www-form-urlencoded',
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
This is get_id.php:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
?>
I have tried also without content types and without json. "var data_item" prints id correct, but php doesn't create session and in console also clear(nothing).
The reason that you are not getting data in session is, you are not assigning proper value to session. Also it should be json_decode not json_encode.
replace
$_SESSION['item_id'] = json_encode($_POST);
with
if (!empty($_POST['id'])) {
$_SESSION['item_id'] = json_decode($_POST['id']); // use json_decode
}
It seems to me that you are making some small mistake in your code like you are echoing $row['p_id'] while your query should return id instead p_id also you are making mistake in ajax you are sending data-type JavaScript assuming your code is subtracting so try to use this code i code below.
// modify your php code
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php } ?>
// modify your jQuery
$(document).on('click', '.open_item', function(event){
var data_item = $(this).data("id");
$.ajax({
url: 'get_id.php',
type: 'POST',
dataType: 'json',
data: { id: data_item },
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
<?php
session_start();
header("Content-Type: application/json", true);
$_SESSION['item_id'] = json_encode($_POST["id"]);
echo json_encode(['data_id' => $_SESSION['item_id']]);
?>
You can use
$_SESSION['item_id'] = json_encode($_POST['id']);
instead of
$_SESSION['item_id'] = json_encode($_POST);
this will work fine.
I don't know what you are trying to do, but from your JS, it looks like that you are expecting that the PHP script --which you post some data to it-- to return a json with the data you have just posted in it. In that case, try this, change your get_id.php to be like:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
echo $_SESSION['item_id'];
?>
I'd troubleshoot this by making sure the click handler is actually going off. Put alert("clicked"); as the first thing in the in the click handler to make sure.
For the meantime, remove the contentType in the json call. Also remove the dataType (data-type) entirely. On the php side, replace the header() line so (as mentioned) the php is just:
session_start();
$_SESSION['item_id'] = $_POST["id"];
echo $_SESSION['item_id'];
Do not use json_encode/decode right now. From your code, it is not needed.
I have a table which consists of data from MYSQL, and whenever I make changes in an element in table, my database will be updated by ajax.
This is my javascript code to send the data in editable row.
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
$("#tabs-1").load(location.href + " #tabs-1");
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
After the function above, saveedit.php will deal with updating the database and it's functional.
Then, this is my table in html and these table elements are editable.
<?php
$result = FUNCTION_TO_RETRIEVE_DATA_FROM_DB;
foreach($result as $k=>$v){
?>
<tr>
<td><?php echo $k+1; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'memberID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["memberID"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'surname', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["surname"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'forename', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["forename"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'address', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["address"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'gradeID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["gradeID"]; ?></td>
</tr>
<?php
}
?>
This code is working, but the question I would like to ask is, how can I validate the data entered by the user into this element? For example, what if I would like to check the initial column, memberID, cannot be longer than 6 characters, or if it is required or not. What I am trying to do is to validate entered data before sending it using AJAX but now but I have no idea how validation can be done in the table element.
Before calling ajax validate your column by putting condition before it.
` function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
$("#tabs-1").load(location.href + " #tabs-1");
if(column == "memberID"){
if(editableObj.innerHTML.length > 6 ) {
alert("cannot be longer than 6 characters");
return false;
}else{
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
}
}`
Before calling the saveToDatabase() function put the desired validation on the entered value like:
var newVal = editableObj.innerHTML;
// Your validation on newVal, if validation successful call the saveToDatabase() function
// Otherwise show an error message and do nothing
Check the passing parameter and only process ajax when your condition is satisfied.
function saveToDatabase(editableObj,column,id) {
//If(editableObj.length > 6) // Case of string Check your other condition.
if(editableObj.toString().length > 6) // in case it is not string.
{
alert(Condition fail);
}
else
{
// Your ajax call -------
}
}
Or :
Check your passing data before calling saveToDatabase function.
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?