Fill multiple fields from click with jquery mysql - php

I do have a dynamic grid that shows items from MySQL table using PHP. I have a icon that is supposed to get data from MySQL based in the id of the current register and fill the fields in the form with related information:
PHP/HTML grid
$output .='<tr id="'.$id.'">';
$output .='<td>'.$description.'</td>';
$output .='<td>'.$description_pt.'</td>';
$output .='<td align="right">US$'.number_format($price, 2, '.', ',').'</td>';
$output .='<td align="center">'.$a_c.'</td>';
$output .='<td align="center">'.$note.'</td>';
$output .='<td align="center">'.$note_pt.'</td>';
$output .='<td align="center" class="icon_grid"><a class="editar" title="Open the register." href="#"><img src="images/Write2.gif" width="16" height="16" /></a></td>';
$output .='<td align="center" class="icon_grid"><a class="delete" title="Delete the register." href="#"><img src="images/Trash.gif" width="16" height="16" /></a></td>';
$output .='</tr>';
The HTML form:
<div id="edita_cadastro">
<form name="form3" id="form3" method="post" action="" >
<table width="50%" border="0" cellspacing="2" cellpadding="0">
<tr>
<td colspan="2"><h3>Edit the current register</h3></td>
</tr>
<tr>
<td align="right"><label for "edt_description"><img src="images/usa.jpg" width="18" height="15" />Description:</label></td>
<td><input type="text" name="edt_description" id="edt_description" size="45" /></td>
</tr>
<tr>
<td align="right"><label for "edt_description_pt"><img src="images/brazil.jpg" width="18" height="15" />Description:</label></td>
<td><input type="text" name="edt_description_pt" id="edt_description_pt" size="45" /></td>
</tr>
<tr>
<td align="right"><label for "edt_price">Price:</label></td>
<td><input type="text" name="edt_price" id="edt_price" size="35" placeholder="ex.: 1.00" /></td>
</tr>
<input type="hidden" name="pack_id" id="pack_id" value="<?php echo $pack_id; ?>" />
<td><input type="hidden" name="editar" value="editar" /></td>
<td><input type="submit" name="submit" id="submit" value="Save" /></td>
</tr>
</table>
</form>
</div>
Now, the PHP get_prices.php
include '../connect_to_mysql.php';
$item_id = $_POST['pk_id']; // Selected item Id
$query = "SELECT * from packages_prices WHERE id='$item_id'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result, MYSQL_ASSOC);
$description = $row['description'];
$description_pt = $row['description_pt'];
$price = $row['edt_price'];
$arr = array( 'edt_description' => $description, 'edt_description_pt' => $description_pt, 'edt_price'=> $price);
echo json_encode( $arr );
Finally, the jQuery script:
$(document).ready(function(e) {
$("#tabela tr[id]").on("click", ".editar", function () { // Tabela is the table's id
var obj = $(this).closest("tr[id]");
$.ajax({
type: "POST",
url: 'get_prices.php',
data: { pk_id: obj.attr("id")},
dataType: "json",
success: function(data, evt) {
if (data.success == "true") {
$("#edt_description").val(data.edt_description);
$("#edt_description_pt").val(data.edt_description_pt);
$("#edt_price").val(data.edt_price);
} else {
alert('error');
}
}
});
});
So, I don't know what may be wrong. The data is not coming and, of course, not filling the fields.
Does anyone knows what is going on?
Thank you

You have a syntax error , your forgot }); at the end of your script , so may it's the reason why it's not working:
<script>
$(document).ready(function(e) {
$("#tabela tr[id]").on("click", ".editar", function () { // Tabela is the table's id
var obj = $(this).closest("tr[id]");
$.ajax({
type: "POST",
url: 'get_prices.php',
data: { pk_id: obj.attr("id")},
dataType: "json",
success: function(data, evt) {
if (data.success == "true") {
$("#edt_description").val(data.edt_description);
$("#edt_description_pt").val(data.edt_description_pt);
$("#edt_price").val(data.edt_price);
} else {
alert('error');
}
}
});
});
});
</script>

Related

Save Edit button then disabled readonly metabox

Hello I am just starting out with php and I have managed to get a repeatable metabox and managed to add a 'Save' button which saves the input meta data to the database which works, how can I change the fields to disabled readonly when the 'Save' button is pressed, and then the 'Save' button becomes 'Edit' which when pressed the fields are editable and the button becomes 'Save'? any help will be appreciated
metabox
add_action( 'wp_ajax_handle_Inventory_in_db', 'handle_Inventory_in_db' );
function mdr_add_meta_boxes() {
add_meta_box( 'mdrinventory-group', 'Inventory', 'Repeatable_meta_box_display', 'rvs_video', 'normal', 'high');
}
function Repeatable_meta_box_display() {
global $post;
global $wpdb;
$sql="SELECT * FROM $wpdb->postmeta WHERE post_id = '".$post->ID."' AND meta_key='inventory_group'";
$allData = $wpdb->get_results($wpdb->prepare($sql));
wp_nonce_field( 'mdr_repeatable_meta_box_nonce', 'mdr_repeatable_meta_box_nonce' );
?>
<script type="text/javascript">
jQuery(document).ready(function( $ ){
$( '#add-row' ).on('click', function() {
var row='';
var data = {
'post_id':'<?=$post->ID?>',
'action': 'handle_Inventory_in_db',
'command': 'add_new_blank_row_in_db',
}
$.post(ajaxurl, data, function(resp){
row=resp;
$('#dynamic-rows').append(row);
});
return false;
});
$('body' ).on('click','.update-row',function() {
var meta_id=$(this).attr('data-uid');
var data = {
'meta_id': meta_id,
'serial': $("#serial_"+meta_id).val(),
'barcode':$("#barcode_"+meta_id).val(),
'action': 'handle_Inventory_in_db',
'command': 'update_row',
}
$.post(ajaxurl, data, function(resp){
console.log(resp);
});
$(this).val('Update');
return false;
});
$('body' ).on('click','.remove-row',function() {
var meta_id=$(this).attr('data-uid');
var data = {
'meta_id': meta_id,
'action': 'handle_Inventory_in_db',
'command': 'remove_row',
}
$.post(ajaxurl, data, function(resp){
console.log(resp);
});
$(this).parents('tr').remove();
return false;
});
});
</script>
<table id="repeatable-fieldset-one" width="100%" class="wp-list-table widefat fixed striped table-view-list">
<thead>
<tr>
<th>Serial No.</th>
<th>Barcode No.</th>
</tr>
</thead>
<tbody id="dynamic-rows">
<?php
if ( $allData ) :
foreach ($allData as $singleRow) {
$save_btn_label= $singleRow->meta_value==''?'Save':'Update';
$meta_value = unserialize( $singleRow->meta_value);
?>
<tr>
<td width="15%"><input type="text" id="serial_<?=$singleRow->meta_id;?>" placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();" value="<?php if($meta_value['serial'] != '') echo esc_attr($meta_value['serial']); ?>" /></td>
<td width="70%"><input type="text" id="barcode_<?=$singleRow->meta_id;?>" placeholder="Barcode" value="<?php if($meta_value['barcode'] != '') echo esc_attr($meta_value['barcode']); ?>" /></td>
<td width="15%"><input data-uid="<?=$singleRow->meta_id;?>" type="button" class="update-row mdr_bk_btn1" value="<?=$save_btn_label;?>"></td>
<td width="15%"><a data-uid="<?=$singleRow->meta_id;?>" class="button remove-row" href="#1">Remove</a></td>
</tr>
<?php
}
else :
// insert a blank row
$meta_id=add_post_meta( $post->ID, 'inventory_group', '', false ); //Add new meta to table and store id in $uid
?>
<tr>
<td width="15%"><input type="text" id="serial_<?=$meta_id;?>" placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();"/></td>
<td width="70%"><input type="text" id="barcode_<?=$meta_id;?>" placeholder="Barcode"/></td>
<td width="15%"><input data-uid="<?=$meta_id;?>" type="button" class="update-row mdr_bk_btn1" value="Save"></td>
<td width="15%"><a data-uid="<?=$meta_id;?>" class="button remove-row" href="#1">Remove</a></td>
</tr>
<?php endif; ?>
</tbody>
</table>
<p><a id="add-row" class="button" href="#">Add Inventory</a></p>
<?php
}
function handle_Inventory_in_db()
{
global $wpdb;
$table_name = $wpdb->prefix . 'postmeta';
$conditions = array( 'meta_id' => $_POST['meta_id'] );
switch ($_POST['command']) {
case 'add_new_blank_row_in_db':
$meta_id=add_post_meta( $_POST['post_id'], 'inventory_group', null, false );
$row='<tr>
<td width="15%"><input type="text" id="serial_'.$meta_id.'" placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();"/></td>
<td width="70%"><input type="text" id="barcode_'.$meta_id.'" placeholder="Barcode"/></td>
<td width="15%"><input data-uid="'.$meta_id.'" type="button" class="update-row mdr_bk_btn1" value="Save"></td>
<td width="15%"><a data-uid="'.$meta_id.'" class="button remove-row" href="#1">Remove</a></td>
</tr>';
echo $row;
break;
case 'update_row':
$serial=$_POST['serial'];
$barcode=$_POST['barcode'];
$meta_value=serialize(array('serial'=> $serial,'barcode'=>$barcode));
$data=array(
'meta_value'=>$meta_value,
);
$result = $wpdb->update( $table_name,$data, $conditions );
echo $response=$result?"The row successfully updated":"There was an error updating the row";
break;
case 'remove_row':
$result = $wpdb->delete( $table_name, $conditions );
echo $response=$result?"The row successfully deleted":"There was an error deleting the row";
break;
default:
echo "Silence is golden";
break;
}
wp_die();
} ``

jQuery / AJAX send content of changed divs

I have this CRUD system where a customer should be able to specify the amount of the desired product. When the amount is > 0, I add a new class "active" to that table row.
When the "continue" button is clicked, the rows containing a value of 0 are filtered out. After clicking the "order" button I want to send an email to the admin containing the list of desired products and the corresponding amount.
The code below works, however, the email sent contains only one field (it must be able to handle several of them) and the amount is always 0.
<form role="form" method="post" action="email.php">
<input type="text" class="sendmail" name="name" placeholder="Your name" />
<input type="text" class="sendmail" name="email" placeholder="Your email" />
</form>
<table>
<tr class='".$row['id']."'>
<td class='name'>".$row['name']."</td>
<td class='category'></td>
<td class='price'>€".$row['price']."</td>
<td class='unit'>per ".$row['unit']."</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='".$row['id']."'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> Volgende</button>
<button id="confirm"><i class="fas fa-paper-plane"></i> Bestellen</button>
jQuery
$(document).ready(function() {
$('input').on('change', function() {
var id = $(this).attr('id');
if(parseInt(this.value) > 0){
$('.'+id).addClass('active');
}
else {
$('.'+id).removeClass('active');
}
});
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
$(':input[type="number"]').prop('disabled', true);
});
});
$(function() {
$('#confirm').click(function(e) {
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': $('.active').html(),
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
email.php
$email = $_POST['email'];
$subject = "Subject";
$name = $_POST['name'];
$content = $_POST['message'];
$to = 'myemail#gmail.com';
$body = '
<html>
<head>
<title>Email: '. $email .'</title>
</head>
<body>
<p>From: '. $name .'</p>
<div>
'. $content .'
</div>
</body>
</html>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= "From: $email\r\n";
mail($to, $subject, $body, $headers);
This is the email I receive:
I've been testing your code.
The first thing I noticed, you are using the ".active" class to reference several elements, which is fine because then you can call them as an array, but using $('.active').html() only returns the first element and NOT the outerhtml for the TR. And you also need the TABLE tags for your mail to have a correct html.
So I would do something like this:
$(function() {
$('#confirm').click(function(e) {
var data = "<table>";
$('.active').each(function(i, obj) {
data += obj.outerHTML;
});
data += "</table>";
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': data,
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
And then when you want to reference the HTML itself to use in the mail maybe you should delete the input and paste the value of the input instead. Because the actual value of the input may not be copied:
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
//$(':input[type="number"]').prop('disabled', true);
$(':input[type="number"]').each(function(i,obj){
obj.after( obj.value );
obj.parentNode.removeChild(obj);
});
});
Here are the sinppets:
$(document).ready(function() {
$('input').on('change', function() {
var id = $(this).attr('id');
if(parseInt(this.value) > 0){
$('.'+id).addClass('active');
}
else {
$('.'+id).removeClass('active');
}
});
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
//$(':input[type="number"]').prop('disabled', true);
$(':input[type="number"]').each(function(i,obj){
obj.after( obj.value );
obj.parentNode.removeChild(obj);
});
});
});
$(function() {
$('#confirm').click(function(e) {
var data = "<table>";
$('.active').each(function(i, obj) {
data += obj.outerHTML;
});
data += "</table>";
console.log(data);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<table>
<tr class='1'>
<td class='name'>lala</td>
<td class='category'></td>
<td class='price'>€125</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='1'></td>
</tr>
<tr class='2'>
<td class='name'>lele</td>
<td class='category'></td>
<td class='price'>€225</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='2'></td>
</tr>
<tr class='3'>
<td class='name'>lili</td>
<td class='category'></td>
<td class='price'>€325</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='3'></td>
</tr>
<tr class='4'>
<td class='name'>lolo</td>
<td class='category'></td>
<td class='price'>€425</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='4'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> ORDER</button>
<button id="confirm" style="display:none;"><i class="fas fa-paper-plane"></i> CONFIRM</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
Hope I can help
First of all, when your are dealing with input type=number you have to update it's attr value manually. Then, according to doc, if you are using jquery html() method against array it takes first element and return it's html. So, in your case you have to do few changes:
$(function() {
$('input').on('change', function() {
$(this).closest('tr').toggleClass('active', parseInt(this.value) > 0);
$(this).attr('value', $(this).val()); // manually set attr value
});
$('#order').on('click', function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not('.active').empty();
$(':input[type="number"]').prop('disabled', true);
});
$('#confirm').click(function(e) {
let messages = [];
$('.active').each(function(el){
messages.push($(this).html());
});
console.log(messages); // composed messages array
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': messages,
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" method="post" action="email.php">
<input type="text" class="sendmail" name="name" placeholder="Your name" />
<input type="text" class="sendmail" name="email" placeholder="Your email" />
</form>
<table>
<tr class='class1'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class1'></td>
</tr>
<tr class='class2'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class2'></td>
</tr>
<tr class='class3'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class3'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> Volgende</button>
<button id="confirm"><i class="fas fa-paper-plane"></i> Bestellen</button>

How to get values from foreach loop of php in jquery

I'm Working on a plugin in Wordpress in which i'm storing values in new table which is created on plugin activation its working perfectly.
Now I fetched values from table like following
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id ?>">
</td>
<td width="26%">
<textarea rows="3" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
after fetching the data I display the values in form of listing.
Now I want to update values of input fields and textarea through ajax for which I wrote following code
add_action('wp_ajax_ajc_update_values', 'ajc_update_value');
add_action('wp_ajax_nopriv_ajc_update_values', 'ajc_update_value');
add_action("admin_head", "ajc_input_ajax");
function ajc_input_ajax()
{
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id = jQuery('.ajc_field_id').val();
var update_link = jQuery('.img_link').val();
var update_desc = jQuery('.img_description').val();
var update_title = jQuery('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
<?php
}
//Updating values in database
function ajc_update_value()
{
$id = $_POST['ajc_id'];
$link = $_POST['ajc_update_link'];
$desc = $_POST['ajc_update_desc'];
$title = $_POST['ajc_update_title'];
global $wpdb;
$wpdb->update(
'wp_ajc_images',
array(
'ajc_img_title' => $title,
'ajc_img_description' => $desc,
'ajc_img_link' => $link
),
array('ajc_img_id' => $id)
)
die();
return true;
}
When I click on first item's update button it alerts me right id eg. (12) and update it, but when I click on rest of the item's update button it alerts me first item's id (12) and data is not updated.
Hope you'll understand my question.
Try this code. add id to every fields like id="img_link_<?php echo $row->ajc_img_id; ?>"
HTML code
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" id="img_link_<?php echo $row->ajc_img_id; ?>" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id; ?>">
</td>
<td width="26%">
<textarea rows="3" id="img_description_<?php echo $row->ajc_img_id; ?>" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" id="img_title_<?php echo $row->ajc_img_id; ?>" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" data-id="<?php echo $row->ajc_img_id; ?>" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
Script code
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id =jQuery(this).attr('data-id');
var update_link = jQuery('#img_link'+id).val();
var update_desc = jQuery('#img_description'+id).val();
var update_title = jQuery('#img_title'+id).val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
You're displaying values based on a class name and there could be many elements with same class name. What you need to do is target specific <tr> and get values from that <tr> only.
So your jQuery code should look like this:
jQuery("#update").click(function () {
var id = $(this).parents('tr').find('.ajc_field_id').val();
var update_link = $(this).parents('tr').find('.img_link').val();
var update_desc = $(this).parents('tr').find('.img_description').val();
var update_title = $(this).parents('tr').find('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
You just have to add $(this).parents('tr').find before selecting values from every element.

Update only fields that have been modified or added by user

I have only added a portion of the full code here. What I want the code to do, is once it is submitted, I only want it to update the fields in the table that have been changed, not every item in every row (as some are NULL value, and need to stay that way).
So ultimately - how would I code the PHP process page.
Table is formatted as heli_cust:
cust_id
cust_fname
cust_lname
cust_kg
cust_email
cust_addr
cust_phone
http://jsfiddle.net/qz7k5caj/
HTML:
<table width="100%">
<div class="form_head">Passengers</div>
<table width="100%" cellpadding="4" cellspacing="0" id="px">
<thead>
<tr class="tab_head">
<td width="25px" style="text-align:center; color:#FFFFFF; font-size:11px;">#</td>
<td class="form_label" style="color:#ffffff; font-size:11px;">Cust#</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">First Name</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Last Name</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Wgt</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Address</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Phone</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Email</td>
<td></td>
</tr>
</thead>
<tbody id="tbl1">
<?php if ($cust = mysql_fetch_assoc($getcust)) {
do { ?>
<tr id="pass">
<td style="vertical-align:middle; text-align:center"><input type="text" name="pass_num[]" readonly="readonly" value="1" class="pass" style="font:Verdana; font-size:11px; border:none; background-color:transparent; width:25px; text-align:center; vertical-align:middle;" tabindex="-1"></td>
<td><input type="text" readonly="readonly" class="form_a" value="<?php echo (int)$cust[cust_id] ?>" style="text-align:right; border:none; background-color:transparent; width:25px" /></td>
<td><input type="text" name="cust_fname[]" class="form_g" value="<?php echo $cust[cust_fname] ?>"/></td>
<td><input type="text" name="cust_lname[]" class="form_g" value="<?php echo $cust[cust_lname] ?>"/></td>
<td><input type="text" name="cust_kg[]" class="form_a" value="<?php echo $cust[cust_kg] ?>"/></td>
<td><input type="text" name="cust_addr[]" class="form_c" style="width:200px" value="<?php echo $cust[cust_addr] ?>"/></td>
<td><input type="text" name="cust_phone[]" class="form_g" value="<?php echo $cust[cust_phone] ?>"/></td>
<td><input type="text" name="cust_email[]" class="form_b" value="<?php echo $cust[cust_email] ?>"/></td>
<td style="vertical-align:middle"><a class="removePax"><img src="images/remove_pax.png" /></a></td>
</tr>
<?php } while ($cust = mysql_fetch_assoc($getcust));
} ?>
</tbody>
</table>
<table width="100%">
<tr><td style="text-align:right"><a id="add"> <img src="images/add_pax.gif"> </a></td></tr>
</table>
<br />
<table width="100%"><tr><td></td><td style="text-align:right"><input type="submit" value="Update" /></td></tr>
</table>
JQuery:
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
$("#tbl1 .removePax").on("click",function() {
if($("#tbl1 tr:last").index() >0) {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(500, function(){
tr.remove();
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
});
return false;
} else {
if($(this).closest('tr').index() == 0) {
$("#tbl1 tr:eq(0)").find("input").each(function(){
if ($(this).hasClass('pass')) {
} else {
$(this).val('');
};
});
};
};
});
$("#add").click(function(){
$("#tbl1 tr:first").clone().find("input").each(function() {
$(this).val('')}).end().appendTo("#tbl1");
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
$(".removePax").on("click",function() {
if($("#tbl1 tr:last").index() >0) {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(500, function(){
tr.remove();
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
});
return false;
} else {
if($(this).closest('tr').index() == 0) {
$("#tbl1 tr:eq(0)").find("input").each(function(){
if ($(this).hasClass('pass')) {
} else {
$(this).val('');
}
}).end();
} else {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(500, function(){
tr.remove();
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
});
return false;
}
};
});
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
});
});
Aside from the idea given by #rjdown, In case you're trying to do it using AJAX, you can add an onchange handler, and add a class "changed" to the changed item. Then, just send all the changed data back to your backend. That way you know for sure what you're to send.

Delete multiple entries with AJAX

I'm able to delete one entry at a time using AJAX. Now I've made the possibility to select entries using a checkbox and delete them all simultaneously, this works great without AJAX. Now I'm trying to delete multiple entries using AJAX. This is what I have so far:
the ajax:
`$(function() {
$(".checkbox_button_del").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parents('tr:first');
var notice = '<div class="notice">'
+ '<div class="notice-body">'
+ '<img src="core/displays/notify/delete-icon.png" alt="" />'
+ '<h3>Deleted item</h3>'
+ '<p>The item has been succesfully deleted.</p>'
+ '</div>'
+ '<div class="notice-bottom">'
+ '</div>'
+ '</div>';
$ny( notice ).purr(
{
usingTransparentPNG: true
}
);
$.ajax({
type: "POST",
url: "core/actions/delete_multiple.php",
data: dataString,
cache: false,
success: function()
{
parent.fadeOut('300', function() {$(this).remove();});
$("#load_tasklist").load("core/statistics/stats_brackets.php")
$("#load_tweets").load("response.php")
$("#load_mod_day_summary").load("core/displays/mod_day_summary.php")
$("#load_mod_task_selector").load("core/displays/mod_task_selector.php")
}
});
return false;
});
});`
the external deleting script:`
include('../../core/additional/connect-db.php');
for($i=0;$i<count($_POST["chkDel"]);$i++)
{
if($_POST["chkDel"][$i] != "")
{
$strSQL = "DELETE FROM players ";
$strSQL .="WHERE id = '".$_POST["chkDel"][$i]."' ";
$objQuery = mysql_query($strSQL);
}
}
header('Location: ' . $_SERVER['HTTP_REFERER']);`
and the result list with the delete button: `
<form name="frmMain" id="myForm" method="post" OnSubmit="return onDelete();">
<?php
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
$result = mysql_query("SELECT * FROM players WHERE (userid = '$username' AND done = '0' AND measure = 'task' AND day = '$user_mydate') ORDER BY id DESC")
or die(mysql_error());
echo '<div id="checkbox_button_div">
<input class="checkbox_button_del" type="submit" id="buttondel" value="Delete" />
<input class="checkbox_button_done" type="submit" id="buttondone" value="Done" />
<input class="checkbox_button_done" type="submit" id="buttonfavorite" value="Favorite" />
<input class="checkbox_button_done" type="submit" id="buttonmove" value="+1 day" />
</div>';
echo '
<table id="tableOne" cellpadding="0" cellspacing="0" width="760" border="0" class="yui">
<thead>
<tr>
<th>Task</th>
<th>Minutes</th>
<th>Time</th>
<th>Category</th>
<th> <input type="checkbox" class="check" value="check all" /></th>
</tr>
</thead>
<tbody> ';
$i = 0;
while($row = mysql_fetch_array( $result )) {
$i++;
include ('core/additional/params_tasks.php');
echo '
<tr class="handcursor" onmouseover="' .($mouseover). '" onmouseout="' .($mouseout). '">
<td class="editable" id="' .($id). '" width="180">' .($task). ' </td>
<td class="editable" id="' .($id). '">' .($minutes). '</td>
<td onClick="' .($onclick). '">' .($hours_start). '.' .($minutes_start). ' - ' .($hours_due2). '.' .($minutes_due2). ' </td>
<td onClick="' .($onclick). '">' .($categorie). ' </td>
<td align="center"><input type="checkbox" class="cb-element" name="chkDel[]" id="chkDel<?=$i;?>" value="' .($id). '"></td>
</tr> ';
}
// close table>
echo '</tbody>
<tfoot>
<tr style="display:none;">
<td style="border: 0px;" colspan="4">
No matching results..
</td>
</tr>
</tfoot>
</table>
';
?>
<input type="hidden" name="hdnCount" value="<?=$i;?>">
</form>`
I think the AJAX script should pass the "$i" values as well, but I don't know how to do this. Please tell me if the problem isn't clear to you. Looking forward to your answer!
yout jquery would be somthing like this.
$("#Submit1").click(function () {
var arr = new Array();
$("input:checked").each(function () {
arr.push($(this).attr("id"));
}); //each
$.ajax({
type: "POST",
url: "core/actions/delete_multiple.php",
data: arr ,//pass the array to the ajax call
cache: false,
success: function()
{ }
});//ajax
}); //each
}); //click
since the PHP function will get a JSON object. you will need to do a JSON decode to ge the array.... see JSON decode... use this array to create your query like..
delete from SalesLT.Customer
where CustomerID in (1,2,3,4);

Categories