Jquery select data-id from second row on table - php

I've been trying to make a table with a list of users for a school project.
I'm doing this with jquery, php and mysql.
I'm retrieving all data from the mysql database and printing it out in a table.
now i'm trying to add an update button to i can easily update data for each specific row.
This however is not working as expected. It only selects the data from the same row. While the data-id value is different. Could anyone tell me why this is happening? I'll leave my code below for clearance
JS:
$(document).ready(function () {
$(document).on('click', '#update-btn', function () {
var id =$("[id='update-btn']").attr('data-id');
var username = $('#username').val();
var dob = $('#dob').val();
var address = $('#address').val();
$.ajax({
url: 'ajax/update.php',
method: 'POST',
data: {
ID: id,
username: username,
dob: dob,
address: address
},
success: function (data) {
if (data){
console.log(data);
swal({
title: 'Update successful',
icon: 'success',
text: 'User with ID ' + id + ' updated.'
});
setTimeout(function () {
window.location = 'medewerkers.php';
}, 5000)
}
else if (data === "update_failed"){
}
}
});
});
});
PHP:
public static function loadMedewerkers(){
$mysql = Database::DBCon()->prepare('
SELECT * FROM medewerkers
');
$mysql->execute();
while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
{
$html = '<tr>
<td><input type="text" value="'. $fetch['username'] .'" id="username"></td>
<td><input type="text" value="'. $fetch['dob'] .'" id="dob"></td>
<td><input type="text" value="'. $fetch['address'] .'" id="address"</td>
<td><button type="button" class="btn btn-danger" id="delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
<button type="button" class="btn btn-warning" id="update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
</tr>';
echo $html;
}
}

The problem is because your loop is causing multiple elements to have the same id, when id attributes must be unique within the DOM. To fix this use common classes on the elements within the loop, then DOM traversal to find them when the button is clicked.
public static function loadMedewerkers()
{
$mysql = Database::DBCon()->prepare('SELECT * FROM medewerkers');
$mysql->execute();
while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
{
$html = '<tr>
<td><input type="text" value="'. $fetch['username'] .'" class="username"></td>
<td><input type="text" value="'. $fetch['dob'] .'" class="dob"></td>
<td><input type="text" value="'. $fetch['address'] .'" class="address"</td>
<td>
<button type="button" class="btn btn-danger delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
<button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
</tr>';
echo $html;
}
}
$(document).ready(function() {
$(document).on('click', '.update-btn', function() {
var $row = $(this).closest('tr');
var id = $(this).data('id');
var username = $row.find('.username').val();
var dob = $row.find('.dob').val();
var address = $row.find('.address').val();
// ajax request here...
});
});
Note the use of data() to retrieve the data attribute. Also note that you could put the data-id attribute itself on the tr instead of each button to DRY up the HTML slightly.

You are using ID in your buttons when returning
ID is unique for each object in the screen
try using class
something like this:
$(document).ready(function () {
$(document).on('click', '.update-btn', function () {
var id =$(this).data('id');
var username = $(this).closest('tr').find('.username').val();
var dob = $(this).closest('tr').find('.dob').val();
var address = $(this).closest('tr').find('.address').val();
$.ajax({
url: 'ajax/update.php',
method: 'POST',
data: {
ID: id,
username: username,
dob: dob,
address: address
},
success: function (data) {
if (data){
console.log(data);
swal({
title: 'Update successful',
icon: 'success',
text: 'User with ID ' + id + ' updated.'
});
setTimeout(function () {
window.location = 'medewerkers.php';
}, 5000)
}
else if (data === "update_failed"){
}
}
});
});
});
public static function loadMedewerkers(){
$mysql = Database::DBCon()->prepare('
SELECT * FROM medewerkers
');
$mysql->execute();
while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
{
$html = '<tr>
<td><input type="text" value="'. $fetch['username'] .'" class="username"></td>
<td><input type="text" value="'. $fetch['dob'] .'" class="dob"></td>
<td><input type="text" value="'. $fetch['address'] .'" class="address"</td>
<td><button type="button" class="btn btn-danger delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
<button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
</tr>';
echo $html;
}
}
same goes for your delete button
and use .data() instead of attr()
Also, in other columns for getting the username, dob and address you have to use class instead of id.

Related

Change specific dynamically created table row html and text from ajax response

From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>

Data not insert and update through ajax and jQuery in admin page?

I made custom plugin and done crud operation, display all data in admin page, used ajax and jquery. Data successfully deleted but not inserted or updated. Data successfully pass through ajax but not inserted. Also What I saw if input block is empty and I put some data and updated it. It got first row data.
Error- https://prnt.sc/wnzqjr
ajax for insert data
<tr>
<td><?php echo $q ?></td>
<td>
<input type="text" name="question" class="question" value="<?php echo $print->question ?>" ></td>
<td>
<input type="text" name="answer" class="answer" value="<?php echo $print->answer ?>" > </td>
<td>
<input type="button" value="Insert" id="insert" data-id = "<?php echo $print->id ?>" name="insert" class="ins_btn">
</td>
<td>
<input type="button" value="Update" id="update" data-id = "<?php echo $print->id ?>" name="update" class="upd_btn">
</td>
<td>
<input type="button" value="Delete" id="delete" data-id = "<?php echo $print->id ?>" name="delete" class="del_btn">
</td>
</tr>
jQuery('.ins_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery('#question').val();
var answer = jQuery('#answer').val();
// alert(id);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'insert_records',
insert_record : id,
insert_question: question,
insert_answer: answer
},
success: function( data ){
alert("Records are successfully insert");
location.reload();
}
});
});
insert query
function insert_records(){
global $wpdb;
$id = $_POST['insert_record'];
$question = $_POST['insert_question'];
$answer = $_POST['insert_answer'];
$db_inserted = $wpdb->insert( $wpdb->prefix.'faqq',
array( 'ID' => $id,
'question' => $question,
'answer' => $answer)
);
}
add_action( "wp_ajax_insert_records", "insert_records" );
add_action( "wp_ajax_nopriv_insert_records", "insert_records" );
ajax for update the data
jQuery('.upd_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery('#question').val();
var answer = jQuery('#answer').val();
alert(question);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'update_records',
update_record : id,
update_question : question,
update_answer : answer
},
success: function( data ){
alert("Records are successfully updated");
location.reload();
}
});
});
update query
function update_records(){
global $wpdb;
// $table_name = $wpdb->prefix.'faqq';
$id = $_POST['update_record'];
$question = $_POST['update_question'];
$answer = $_POST['update_answer'];
$db_updated = $wpdb->update( $wpdb->prefix.'faqq',
array('question' => $question,
'answer' => $answer, array( 'ID' => $id ) )
);
}
Here are some errors. 1)Getting error when update the data through ajax- https://prnt.sc/wnymkx, https://prnt.sc/wnyos5, https://prnt.sc/wnyuhk
The problem might be that your loop which is creating the list for displaying on admin page is causing multiple elements to have the same id, when id attributes must be unique within the DOM. To fix this use common classes on the elements within the loop, then DOM traversal to find them when the button is clicked.
Change the code block for display like this:
$mysql = Database::DBCon()->prepare('SELECT * FROM table_name');
$mysql->execute();
while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC)){
$html = '<tr>
<td><input type="text" value="'. $fetch['question'] .'" class="question"></td>
<td><input type="text" value="'. $fetch['answer'] .'" class="answer"></td>
<td>
<button type="button" class="btn btn-danger insert-btn" data-id="'. $fetch['ID'] .'">Insert</button>
<button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
</tr>';
//echo $html;
}
Then change implementation of function to something like this:
$(document).ready(function() {
$(document).on('click', '.update-btn', function() {
var $row = $(this).closest('tr');
var id = $(this).data('id');
var question= $row.find('.question').val();
var answer = $row.find('.answer').val();
// ajax request here...
});
})
i think you forgot to enqueue your script file where jQuery is written. that's it is showing script called incorrectly
you suppose to register your script by admin_enque_script hook
Don't need id field for inserting data, So I remove it. I use classes for question and answer fields.
jQuery('.ins_btn').click(function(){
var question = jQuery(this).closest('tr').find('.question').val();
var answer = jQuery(this).closest('tr').find('.answer').val();
// alert(question);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action : 'insert_records',
insert_question : question,
insert_answer : answer
},
success: function( data ){
location.reload();
}
});
});
Same as for update function, only add reference id field. Because for updating the data, reference Id is important.
jQuery('.upd_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery(this).closest('tr').find('.question').val();
var answer = jQuery(this).closest('tr').find('.answer').val();
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'update_records',
update_record : id,
update_question : question,
update_answer : answer
},
success: function( data ){
location.reload();
}
});
});
And in update query, I added parenthesis at wrong position.
function update_records(){
global $wpdb;
// echo "<pre>"; print_r($_POST);
// die();
// $table_name = $wpdb->prefix.'faqq';
$id = $_POST['update_record'];
$question = $_POST['update_question'];
$answer = $_POST['update_answer'];
$db_updated = $wpdb->update( $wpdb->prefix.'faqq',
array('question' => $question,
'answer' => $answer
),
array( 'ID' => $id )
);
// $wpdb->query($wpdb->prepare("UPDATE $table_name SET question = '$question', answer = '$answer' WHERE id = $id"));
}
add_action( "wp_ajax_update_records", "update_records" ); //update_records is action
add_action( "wp_ajax_nopriv_update_records", "update_records" );

status update on nested statement partially working

Please I need help to figure out why my code below isn't working. I'm not very good at PHP and ajax to start with but find it difficult to figure out why the code below wouldn't function properly.
What it does: changes data in database to 'Disable' but to update to 'Enable' on-click wouldn't work. Please help!
status.php
<?php
session_start();
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="User"){
header('location:index.php');
}
$select=$pdo->prepare("select * from tbl_user order by userid desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ) ){
if (isset($_POST['ridd'])){
$id=$_POST['ridd'];
if($row->user_status == 'Enable'){
$status_str="Disable";
$sql="UPDATE `tbl_user` SET `user_status` = ? WHERE userid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$status_str, $id]);
}else if($row->user_status == 'Disable'){
$status_str2="Enable";
$sql="UPDATE `tbl_user` SET `user_status` = ? WHERE userid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$status_str2, $id]);
}else{
echo'Internal loop error in Updating';
}
}
}
registration.php
<script>
$(document).ready(function() {
$('.switch').click(function() {
var tdh = $(this);
var id = $(this).attr("id");
swal({
title: "Do you want to Change user status?",
text: "Once changed, it can be reversed!",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
$.ajax({
url: 'status.php',
type: 'POST',
data: {
ridd: id
},
success: function(data) {
//tdh.parents('tr').load;
}
});
swal("User status has been changed!", {icon: "success",});
window.location.reload(true);
} else {
swal("No action performed!");
window.location.reload(true);
}
});
});
});
</script>
here is my table code in registration.php
<tbody>
<?php
$select=$pdo->prepare("select * from tbl_user order by userid desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ) ){
$status='Disable';
$colour="btn-danger";
if($row->user_status == 'Enable'){
$status='Enable';
$colour="btn-success";
}
echo'
<tr>
<td>'.$row->userid.'</td>
<td>'.$row->username.'</td>
<td>'.$row->user_status.'</td>
<td>
<div id='.$row->userid.' class="switch">
<button type="button" class="btn '.$colour.'">'.$status.'</button>
</div>
</td>
<td>
<button id='.$row->userid.' class="btn btn-danger btndelete" ><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
';
}
?>
</tbody>
When I click on button 'switch', I'm able to perform a toggle function so that it can update either 'Enable' or 'Disable' on my database. At the moment, only the disable is working and I have to manually enable the user from the database (phpmyadmin).
You can check if the button which is clicked has class btn-success if yes then now we need disable it or else enable so send this as well in your ajax call and at your backend get it using $_POST["status"] and update same . Also, you don't need to reload page instead inside your success function of ajax just change the button using .html().
Demo code :
$(document).ready(function() {
$('.switch').click(function() {
var tdh = $(this);
var id = $(this).attr("id");
swal({
title: "Do you want to Change user status?",
text: "Once changed, it can be reversed!",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
var button_status = $(this).find("button").hasClass("btn-success") ? "Disable" : "Enable"; //check if button has success means we need disable it now else enable .
/*$.ajax({
url: 'status.php',
type: 'POST',
data: {
ridd: id,
status: button_status //send to chnage
},
success: function(data) {*/
//if disable
if (button_status == "Disable") {
$("#" + id).html("<button type='button' class='btn btn-danger '>Disable</button>") //put enable button
tdh.closest("tr").find("td:eq(2)").text("Disable")
} else {
$("#" + id).html("<button type='button' class='btn btn-success '>Enable</button>") //disable buttn
tdh.closest("tr").find("td:eq(2)").text("Enable")
}
/* }
});*/
swal("User status has been changed!", {
icon: "success",
});
} else {
swal("No action performed!");
}
});
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>
<table class="table">
<tbody>
<tr>
<td>1</td>
<td>sw</td>
<td>Enable</td>
<td>
<div id='1' class="switch">
<button type="button" class="btn btn-success ">Enable</button>
</div>
</td>
<td>
<button id='1' class="btn btn-danger btndelete"><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
<tr>
<td>2</td>
<td>sw</td>
<td>Disable</td>
<td>
<div id='2' class="switch">
<button type="button" class="btn btn-danger ">Disable</button>
</div>
</td>
<td>
<button id='2' class="btn btn-danger btndelete"><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
</tbody>
</table>

Ajax Jquery form submit

Hello I am running a form using ajax submit functions using PHP and JS
bellow is my code
submit.php
<?php
if(isset($_POST['add_data'])){
echo "add id";
}
if(isset($_POST['update_data'])){
echo "update_id";
}
?>
Form.js
$('form.data').on('submit',function(){
var info = $(this),
url = info.attr('action'),
method = info.attr('method'),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
form.php
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button name="add_data" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>
<button name="update_data" value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
however the result I am getting is not correct if I click one of the button the console replies:
add idupdate_id
instead of one of the following
add id
or
update_id
On submit you are going to have the value set so isset will always return true. What you must do is:
if(!empty($_POST['add_data'])){
echo "add id";
}
The problem is that your form contains both add_data and update_data, so they will be always set in $_POST. If you want different action for each button, you could assign a function to the onClick event to both buttons, check which caused the event and pass it to your AJAX data.
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button name="add_data" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>
<button" name="update_data" value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
Then in your JS:
$("button").click(function(){
var info = $(this),
url = info.attr('action'),
method = info.attr('method'),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
data["action"] = ($(this).attr("name") === "add_data") ? 0 : 1; //If add_data -> 0 else -> 1
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
And then in your PHP, you look for $_POST["action"] variable
if($_POST["action"] == 0) {
echo "add_data";
} else {
echo "update_data";
}
EDIT: If you would like to, you don't have to check it in a condition, and just past the name attribute to data["action"] and then check in PHP, if $_POST["action"] is equal to add_data or update_data
Use next code for separating your button actions:
HTML:
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button value="add" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>Add</button>
<button value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
JS:
$('form.data > button').on('click',function(){
var info = $(this).parent(),
url = info.attr('action'),
method = info.attr('method'),
task = $(this).val(),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
data['task'] = task;
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
PHP:
if(isset($_POST['task']) && $_POST['task'] == 'add'){
echo "add id";
}
if(isset($_POST['task']) && $_POST['task'] == 'update'){
echo "update_id";
}

Remove Label Tag / Add Input textBox Using Jquery/Bootstrap

I have a column in Database with name URL and ID(PK) i'm using PHP/MYSQL
Im displaying values from db now i want to perform EDIT(update) operation Using Jquery/Ajax.
When i click on Edit link it is replaced with Update/Cancel links Which is working fine and im able to perform update operations.
My requirement is when i click on edit Url data which im using lable tag should replace with input textbox and i should perform update operation
HTML Code
<div class='col-md-4'>
<label class="feed_label" id="feed_label" idl='<?php echo $row->id;?>'><?php echo $row->url; ?></label>
<input name="url1" class="form-control url1 feed_text" value="<?php echo $row->id;?>" id="url1" type="text" placeholder="enter url" style="display:none;">
</div>
<div class='col-md-2'>
<a ide='<?php echo $row->id;?>' id="edit" class='edit' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update btn btn-primary btn-sm' href='#' style='display:none;'>UPDATE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancel btn btn-warning btn-sm' href='#' style='display:none;'>CANCEL</a>
</div>
JQUERY CODE
JQUERY CODE
//EDIT,DELETE TO UPDATE,CANCEL
$('body').delegate('#edit','click',function(){
//alert();
$(this).siblings('#delete').hide();
$(this).siblings('#update,#cancel').show();
$(this).hide();
$('#feed_label').removeClass('feed_label').addClass('feed_url');
});
$('body').delegate('#cancel','click',function(){
//alert();
$(this).siblings('#edit,#delete').show();
$(this).siblings('#update').hide();
$(this).hide();
$("#update_url")[0].reset();
});
//ENDS
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
//alert(IdEdit);
//return false;
$.ajax({
url:"pages/feeds.php",
type:"post",
datatype:"json",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
//alert('success');
$('#id').val(show.id);
$('#url1').val(show.url);
//$('#add_feed_form')[0].reset();
//$('#showdata').load('pages/feeds.php');
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
//alert('update');
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
//alert();
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
//alert('updated');
$('input[type=text]').val('');
showdata();
$('#add_feed_form')[0].reset();
$('#showdata').load('pages/feeds.php');
}
});
});
//UPdate Ends
PHP Code
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
//Ends
Any help Is appreciated Thanks!!
Here i give sample for your case :
HTML
<div class="container">
<label>John</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
<hr/>
<div class="container">
<label>John Who</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
JS (you can simplified below code into one handler)
$(document).on('click', '.edit', function(e){
var data = $(this).prev();
if ( data.is('label') ) data.replaceWith('<input value="'+data.text()+'">');
});
$(document).on('click', '.delete', function(e){
var data = $(this).prev().prev();
if ( data.is('input') ) data.replaceWith('<label>'+data.val()+'</label>');
});
DEMO

Categories