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.
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,
};
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 multiple rows generated into my page using PHP and MySQL, and I have a simple form that helps me to add more rows to database. What I want exactly is, that I have to add a row before a specific row with a specific id:
foreach($resInst as $installment){
$sum = $sum + $installment['payment'];
?>
<tr id="<?php echo $installment['infoid'] ?>"><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
<td><?php echo $counter--; ?></td>
<td><?php echo $installment['date_now'] ?></td>
<td><?php echo $installment['payment'] ?> $</td></tr>
</tr>
<?php } ?>
Here is the AJAX script:
$(document).on('click', '#add_payment', function()
{
var date_of_pay = $("#date_pay_now").val();
var pay_now = $("#pay_now").val();
//var id_pay = $(this).closest('tr').attr('id');
var id_pay = $("#select_to_pay").val();
var pid2 = '<?php echo $patient_id ?>';
console.log(pid2);
if(date_of_pay == "" || pay_now == "" || id_pay)
{
$("#date_pay_now").css('border-color', 'red');
$("#pay_now").css('border-color', 'red');
$("#select_to_pay").css('border-color', 'red');
}
if(date_of_pay != "" && pay_now != "" && id_pay != 0)
{
$.ajax
({
url: 'add_payment.php',
type: 'post',
data: {pid: pid2, date_o_pay: date_of_pay, pay_n: pay_now, id_of_proj: id_pay},
dataType: 'text',
success:function(result)
{
alert("Payment added!");
//Append here
},
error:function(result)
{
alert("Payment didn't added! Please Try again");
}
});
}
});
I mean that when I add information into database that have the same infoid I need to append this new line before the <tr> that have had the same $installment['infoid'].
The problem for me is how to put a condition inside jQuery that said:
if row of the id == id_pay ==> append before this line exactly
Like this:
success:function(result)
{
alert("Payment added!");
if($("tr").prop('id') == id_pay)
{
$(this).before("<tr><td>"+id_pay+"</td></tr>");
}
},
Something like this?
$('#'+id_pay).prev().after( put_your_inner_html_here )
Although, that might be interesting if your row was the first row ... but should still be ok since prev() would be the tbody
I need to update a row of a table. So when I click on a cell, I want it to be transformed into text box, so I used this:
<td contenteditable></td>
And then, when the content of a <td> is changed, I need to send it through AJAX to update it in the server without clicking on a button, so it will use the .change(function()).
I tried to get the content changed into a variable:
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = '<?php echo $row['id'] ?>';
var name = $("#emp_name").val();
var position = $("#position").val();
var salary = $("#salary").val();
$.ajax
({
url: 'update.php',
type: 'POST',
data: {dataId: rowid, data1: name, data2: position, data3: salary},//Now we can use $_POST[data1];
dataType: "text",
success:function(data)
{
if(data=="success")
{
//alert("Data added");
$("#before_tr").before("<tr><td>"+emp+"</td><td>"+pos+"</td><td>"+sal+"</td></tr>");
$("#emp_name").val("");
$("#position").val("");
$("#salary").val("");
}
},
error:function(data)
{
if(data!="success")
{
alert("data not added");
}
}
});
});
The problem is how to know which row is changed to send it via AJAX ? I am not getting any errors even when data not updated.
Here is the update.php code:
try
{
$rowid = $_POST['dataId'];
$emp_name = $_POST['data1'];
$pos = $_POST['data2'];
$sal = $_POST['data3'];
$upd = "UPDATE emp SET name = :emp_name, position = :pos, sal = :sal WHERE id = :rowid";
$updStmt = $conn->prepare($upd);
$updStmt->bindValue(":rowid", $rowid);
$updStmt->bindValue(":emp_name", $emp_name);
$updStmt->bindValue(":pos", $pos);
$updStmt->bindValue(":sal", $sal);
$updStmt->execute();
echo "success";
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
HTML:
<tbody>
<?php
$sql = "SELECT * FROM employee";
$stmt=$conn->prepare($sql);
$stmt->execute();
$res=$stmt->fetchAll();
foreach($res as $row){
?>
<tr id=""<?php echo $row['id'] ?>"">
<td contenteditable><?php echo $row['emp_name'] ?></td>
<td contenteditable><?php echo $row['position'] ?></td>
<td contenteditable><?php echo $row['salary'] ?></td>
</tr>
<?php } ?>
When loading your data with PHP you need to keep the row id in your html:
<tr id="<?php echo $yourList["id"]; ?>">
<td contenteditable></td>
</tr>
Then in your javascript you can catch it using the parent() jquery function
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid =$(this).parent().attr("id");
......
UPDATE
Check this example, I have added listeners to detect contenteditable td changes, I think you shall add it too , refer to this contenteditable change events for defining proper change events on contenteditable fields.
Explanation:
The contenteditable does not trigger change events, this work around is used to detect the focus event of the td using jquery on method and event delegation. The original content is saved in the td jquery data object $this.data('before', $this.html()); . Then when the user leaves the field or triggers any of the events 'blur keyup paste input', the current content is compared to the content in the data object, if it differs, the change event of the td is triggered.
$(document).ready(function(){
$('table').on('focus', '[contenteditable]', function() {
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).on('blur keyup paste input', '[contenteditable]', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
return $this;
});
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = $(this).parent().attr("id");
$("#res").html(rowid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="500px">
<tr id="1222">
<td contenteditable></td>
</tr>
<tr id="55555">
<td contenteditable></td>
</tr>
</table>
Row Id : <span id="res"></span>
<tr row_id="<?php echo $row['id'] ?>"> ></tr>
In Your Ajax
var rowid = $(this).attr('row_id');
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?