In each row, i want to add a editable td to insert "mavandon" into DATABASE dsdonhang. I read this on http://phppot.com/php/php-mysql-inline-editing-using-jquery-ajax/ but it doesn't work :((
<script src="../lib/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function(){
function saveToDatabase(editableObj,column,idd) {
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+$(this).column+'&editval='+$(this).editableObj.innerHTML+'&idd='+$(this).idd,
success: function(data){
$(editableObj).css("background","#FDFDFD");
//alert ("hello");
}
error: function() {}
});
}
});
</script>
<?php $query = mysqli_query($conn,"SELECT * FROM dsdonhang");
while($row=mysqli_fetch_assoc($query)) {$data[] = $row;}
foreach($data as $k=>$v) {
?>
<tr>
<td><?php $madon = $data[$k]["idd"];echo $k+1; ?></td>
<td><?php echo $data[$k]["ngaydat"]; ?></td>
<td><?php echo $data[$k]["hoten"]; ?></td>
<td><?php echo $data[$k]["diachi"]; ?></td>
<td><?php echo $data[$k]["sdt1"]; ?></td>
<td><?php echo $data[$k]["donhang"]; ?></td>
<td><?php echo $data[$k]["tongtien"]; ?>.000VNĐ</td>
<td><?php echo $data[$k]["nguoinhan"]; ?></td>
<td contenteditable="true" onchange="saveToDatabase(this,'mavandon','<?php echo $madon; ?>')"><?php echo $data[$k]["mavandon"]; ?></td>
<td>Xem</td>
</tr>
<?php
}
?>
saveedit.php
<?php
require_once("../lib/connection.php");
mysqli_query($conn,"UPDATE dsdonhang set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE idd='".$_POST["idd"]."'");
?>
Any help? Thanks
use onblur instead of onchange
<td contenteditable="true" onblur="saveToDatabase(this,'mavandon','<?php echo $madon; ?>')" onClick="showEdit(this);"><?php echo $data[$k]["mavandon"]; ?></td>
Typo / incorrect while passing params in the ajax call. Modify it as mentioned below
add this in ajax call.
'&idd='+idd
Instead of this
'&idd='+$(this).idd
Make sure that ur event is getting called.(u can check in firebug also.)
Pass parameters as
{column: $(this).column,editval:$(this).editableObj.innerHTML,idd:$(this).idd}
Try this:
<script>
$(document).ready(function(){
function saveToDatabase(editableObj,column,idd) {
var data = {'column':$(this).column,'editval':$(editableObj).text(),'idd':$(this).idd };
$.ajax({
url: "saveedit.php",
type: "POST",
contentType: "application/json; charset=utf-8",
datatType: "json",
data:JSON.stringify(data),
success: function(data){
$(editableObj).css("background","#FDFDFD");
console.log("received data=>"+data);
alert ("hello");
}
error: function(err) {
console.log("error=>"+err); //print error if exist
}
});
}
});
</script>
Related
I usually figure things out for myself but this one is giving me a really difficult time. I need to change the text value of a button in a table that is created by php from a database, after it gets clicked on.
<td id="order_num"><?php echo $order -> order_num; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<!-- **** this is the button. ******** -->
<td><button type="submit" class="accept_order" id ="row_<?php echo $order -> order_num; ?>"
data-row_id = "row_<?php echo $order -> order_num; ?>" data-current_user = "<?php echo $user_id; ?>"
data-order_num = "<?php echo $order -> order_num; ?>">Accept</button>
here is the big mess of an ajax call
$(document).ready(function () {
$('.shop').on('click', 'button', function(e){
var button = $(this).find('button'); //trying to put the value of the current button in a variable to pass to the ajax function.
var current_user = $(this).closest('.shop').find('.accept_order').data('current_user');
console.log(current_user);
var row_id = $(this).closest('.shop').find('.accept_order').data('row_id');
var accepted_order = $(this).closest('.shop').find('.accept_order').data('order_num');
console.log(accepted_order);
e.preventDefault();
$.ajax('url', {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$(this).html('accepted'); or
$(this).closest('.shop').find('button').html(msg); or
button.text(msg);
},
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}
});
});
});
</script>
I did use $('button').html(msg);
but that changes all of the buttons. It seems like I lose scope to the object when inside the success function. Any ideas or help will be greatly appreciated. Thanks in advance.
I believe I found your problem source but I'm not sure. And The problem came from this keyword because this in the ajax function direct to the ajax object not the button node object. So you can use bind function in the success and error functions to make this directs to the button. here is the modification:
and another thing the url in ajax function is a variable not a string as you wrote above.
$.ajax(url, {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$(this).html('accepted'); or
$(this).closest('.shop').find('button').html(msg); or
button.text(msg);
}.bind(this),
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}.bind(this)
});
I'm not sure from the solution because there is no demo for what you asked about.
I hope it works.
Maybe you can use the class to select the button
$.ajax('url', {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$("button.accept_order").html(msg);
},
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}
});
or better..
var button = $(this);
and inside your ajax call just use:
button.html(msg);
Here is my UI Screenshot. Highlighted is the Dropdown
What i want?
As i Select any option in the Dropdown it should get updated for that particular row in Database using AJAX
Below are the Codes that i've written. I'm just a Beginner, please excuse if the code is not neat!!
I'm using Codeigniter
Front End
<?php if( is_array( $fbrecords ) && count( $fbrecords ) > 0 )
foreach($fbrecords as $r) { ?>
<tr>
<td><?php echo $r->fullname; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->mobile; ?></td>
<td><?php echo $r->message; ?></td>
<td><?php echo $r->jtime; ?></td>
<td> <?php $data=array(
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
$data_status = array(
'none' => 'none',
'A&A' => 'Attended & Acted',
'YTA' => 'Yet to Attend',
);
echo form_dropdown($data, $data_status, set_value('status')); ?> </td>
Ajax Code - I've added a Console.log to see weather next row dropdown is being selected or not
$(document).ready( function() {
$(".statusClass").change(function(event) {
//var dropDown = document.getElementById("status");
//var status = dropDown.options[dropDown.selectedIndex].value;
var status = $("select.statusClass").val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit",
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Controller
public function user_data_status_submit(){
$data = array(
'status' => $this->input->post('status'),
);
//Either you can print value or you can send value to database
echo json_encode($data);
$this->login_database->feedback_update($data);
}
*Console Ouputs for the first 3 rows show the 1 row selection thrice - Below is the Screeshots of that *
You are checking the values of all select box. Instead of that you get the values which you are updating to obtain the result this keyword will use.
$(document).ready( function() {
$(".statusClass").change(function(event) {
var status = $(this).val();
When I am using this code it goes in success else condition and show error. But when I refresh the page the record is deleted automatically.
Please suggest me what I can do.
jquery script:
<script>
$(document).ready(function(){
$(".delete").click(function(event){
alert("Delete?");
var href = $(this).attr("href")
var btn = $(this);
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
event.preventDefault();
})
});
</script>
View file:
<table style="width:100%" border="1" class="table">
<thead>
<tr>
<th>score Id</th>
<th>student name </th>
<th>subject Name</th>
<th>student marks</th>
<th>Action</th>
</tr>
</thead>
<?php foreach($score as $r): ?>
<tbody>
<tr><td><?php echo $r->score_id; ?></td>
<td><?php echo $r->student_name; ?></td>
<td><?php echo $r->subject_name; ?></td>
<td><?php echo $r->marks; ?></td>
<?php if($status <> 1): ?>
<?php if($admin_id == $r->admin_id): ?>
<td><a class="btn btn-info" href="<?php echo base_url(); ?>index.php/score_listing/edit/<?php echo $r->score_id; ?>" > Edit</a><a class="btn delete btn-danger" href="<?php echo base_url(); ?>index.php/score_listing/delete/<?php echo $r->score_id; ?>"> Delete</a></td>
<?php endif; ?>
<?php else: ?>
<td><a class="btn btn-info" href="<?php echo base_url(); ?>index.php/score_listing/edit/<?php echo $r->score_id; ?>" > Edit</a><a class="btn delete btn-danger" href="<?php echo base_url(); ?>index.php/score_listing/delete/<?php echo $r->score_id; ?>" > Delete</a></td>
<?php endif; ?>
</tr>
</tbody>
<?php endforeach; ?>
</table>
Controller file:
public function delete($id)
{
$admin_name = $this->session->userdata('admin_name');
log_message('debug',"this record deleted by Admin = ".$admin_name );
$score = $this->score->delete_operation($id);
$error_data = array('error' => 'Error while deleting record');;
return json_encode(array("success" => true));
}
Just change your controller function's last line:
return json_encode(array("success" => true));
to
echo 'Success';
update you controller function as,
public function delete($id) {
...
...
die('Success');
}
I just tried the below condition in script for ajax and it works. I think I am not confirming or not taking response so thats why it continuously going into else condition where error is written.
Hope this will help some one.
MY new script
<script>
$(document).ready(function(){
$(".delete").click(function(event){
var del = confirm("Delete record?");
var href = $(this).attr("href")
var btn = $(this);
if(del == true)
{
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response != "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
}
event.preventDefault();
})
});
</script>
Your ajax return an object so you cant use if (response == "Success") like this.
change code like this:
public function delete($id)
{
$admin_name = $this->session->userdata('admin_name');
log_message('debug',"this record deleted by Admin = ".$admin_name );
$score = $this->score->delete_operation($id);
$error_data = 2;
echo 1;
}
if it's true it return 1, so chage ajax like this:
if (parseInt(response)==1)
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
I assumed you want hide tr if response is true.
Because you passed it as an array (in javascript it will be converted as an object), the value of the response will be available as response.success. You can check the response object if you write it to the console.
Try this in your ajax method:
success: function(response) {
console.log(response);
if (response.success == true)
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
EDIT:
And I suggest you to change the output in your controller's method:
$this->output->set_content_type('application/json')->set_output(json_encode(array("result" => true)));
instead of
return json_encode(array("success" => true));
I have a PHP snippet that generates a table and fills it, and adds a delete button at the end of each row.
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><form action='delete.php' method='post'><button type='submit' value=$num name='deleteId'>delete</button></form></td>";
echo "</tr>";
}
The delete.php file is this one :
<?php
$host="localhost";
$username="root";
$password="";
$db_name="students";
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$id = $_POST['deleteId'];
$sql="DELETE FROM students WHERE id='$id'";
$result=mysql_query($sql);
?>
I want to do this using Ajax asynchronously, ie. I don't want my page to refresh. Tried a million ways, yet it fails each time. Thanks in advance.
Instead of using a form, you need to write your own JavaScript to handle the server call. Here's one way to do it. Make your PHP look something like this:
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button onclick="deleteStudent($num)">delete</button></td>";
echo "</tr>";
}
And then have a JS function that looks something like this:
function deleteStudent(studentId) {
$.ajax({
url: "delete.php",
method: 'post',
data: {
deleteId: studentId
}
});
}
Another way:
Firstly, assign a unique ID for each of the delete button.
while($row = mysql_fetch_array($result)){
$num = $row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button id='delete-" . $row['id'] . "'>delete</button></td>";
echo "</tr>";
}
Then use jQuery:
$('button[id^="delete"]').click(function () {
var id = $(this).attr('id').substr(6);
$.ajax({
type: "POST",
url: "delete.php",
data: {deleteId: id}
});
});
I am using codeigniter to load data on datatables, on the data table each row has a link that when clicked data is sent elsewhere. The data in that particular row should disappear and only links that have not been clicked remain. I have managed to do that with AJAXbut on success i am forced to reload the page on jQuery timeout
sample:
//Table headers here
<tbody class="tablebody">
<?php foreach ($worksheets as $sheets) : ?>
<tr>
<td><?php echo $sheets->filename ?></td>
<td class="bold assign">
<?php echo $sheets->nqcl_number ?>
<?php echo anchor('assign/assing_reviewer/' . $sheets->nqcl_number, 'Assign') ?>
<a id="inline" href="#data">Assign1</a>
<input type="hidden" id="labref_no" value="<?php echo $sheets->nqcl_number; ?>" />
</td>
<td><?php echo $sheets->uploaded_by ?></td>
<td><?php echo $sheets->datetime_uploaded ?></td>
<td></td>
</tr>
<?php endforeach; ?>
</tbody>
I would like that on AJAX success, the row of the datatables where the link was is dynamically removed from the table without page refresh.
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>assign/sendSamplesFolder/" + labref,
data: data1,
success: function(data) {
var content = $('.tablebody');
$('div.success').slideDown('slow').animate({opacity: 1.0}, 2000).slideUp('slow');
$.fancybox.close();
//Reload the table data dynamically in the mean time i'm refreshing the page
setTimeout(function() {
window.location.href='<?php echo base_url();?>Uploaded_Worksheets';
}, 3000);
return true;
},
error: function(data) {
$('div.error').slideDown('slow').animate({opacity: 1.0}, 5000).slideUp('slow');
$.fancybox.close();
return false;
}
});
I have tried this but it loads two same pages. what's the work around?
content.load(url);
You can use fnDraw() to force the datatable to re-query the datasource. Try this:
// store a reference to the datatable
var $dataTable = $("#myTable").dataTable({ /* Your settings */ });
// in the AJAX success:
success: function(data) {
$dataTable.fnDraw();
},
Have a read of the fnDraw entry in the documentation.
var $dataTable = $("#myTable").dataTable({ /* Your settings */ });
var oSettings = $dataTable.fnSettings();
var page = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength);
$dataTable.fnPageChange(page);