PHP + JAVASCRIPT SAVE DATA - php

This is the controller:
public function routeupdateAction() {
$iRoute = IV_Http_Base::getParameter( 'id', IV_Http_Base::HTTP_POST );
$sPath = IV_Http_Base::getParameter( 'path', IV_Http_Base::HTTP_POST );
$sModule = IV_Http_Base::getParameter( 'module', IV_Http_Base::HTTP_POST );
$sController = IV_Http_Base::getParameter( 'controller', IV_Http_Base::HTTP_POST );
$sAction = IV_Http_Base::getParameter( 'action', IV_Http_Base::HTTP_POST );
$iAccessRole = IV_Http_Base::getParameter( 'accessRole', IV_Http_Base::HTTP_POST );
$iRoleCompareOperator = IV_Http_Base::getParameter( 'roleCompareOperator', IV_Http_Base::HTTP_POST );
$oRoute = Default_Model_RouteEntity::getInstanceById( $iRoute );
if( is_object( $oRoute ) && $oRoute instanceof Default_Model_RouteEntity ) {
$oRoute->setPath( $sPath );
$oRoute->setModule( $sModule );
$oRoute->setController( $sController );
$oRoute->setAction( $sAction );
$oRoute->setAccessRole($iAccessRole);
$oRoute->setRoleCompareOperator($iRoleCompareOperator);
$oRoute->save();
$aReturn = array( 'valid' => 'true' );
} else {
$aReturn = array( 'valid' => 'false' );
}
echo json_encode( $aReturn );
}
}
The route.js file
var ROUTE = new function () {
var oGlobal = this;
this.sSaveUrl = '';
this.setSaveUrl = function (_sUrl) {
this.sSaveUrl = _sUrl;
}
this.setEventSubmit = function () {
$('[id^="route_update"]').each(function () {
$(this).click(function () {
var oData = $(this).closest('tr').find('input').serializeArray();
console.log(oData);
oReq = $.post(oGlobal.sSaveUrl, oData, function (data) {
if (data['valid'] != "true") {
//console.log('error');
//Fade in
$('#comment').html('Insert Success').fadeIn(1000);
//Fade out
setTimeout(function () {
$('#comment').html('').fadeOut(1000);
}, 1500);
//fade in
$('#comment')
} else {
// console.log('success');
//Fade in
$('#comment').html('Insert Success').fadeIn(1000);
//Fade out
setTimeout(function () {
$('#comment').html('').fadeOut(1000);
}, 1500);
//fade in
$('#comment')
}
return false;
}, 'json');
return false;
});
});
}
this.init = function () {
this.setEventSubmit();
}
}
and the html markup
<form class="form-inline" role="form">
<form class="well form-inline">
<table class="table table-bordered" width="100%">
<tr>
<th width="13%">Path</th>
<th width="13%">Module</th>
<th width="13%">Controller</th>
<th width="13%">Action</th>
<th width="13%">Access Role</th>
<th width="13%">Compare Operator</th>
<th width="9%">Submit</th>
</tr>
<?
$aRoutes = $this->getValue('aRoutes');
if( count($aRoutes) == 0 ) {
?>
<tr>
<td colspan="7">No routes found!</td>
</tr>
<?
} else {
/**
* #var Default_Model_RouteEntity $oRoute
*/
foreach ( $aRoutes as $oRoute) {
?>
<tr>
<td width="13%">
<input type="text" name="path" value="<?= $oRoute->getPath(); ?>"/>
</td>
<td width="13%">
<input type="text" value="<?= $oRoute->getModule(); ?>"/>
</td>
<td width="13%">
<input type="text" value="<?= $oRoute->getController(); ?>"/>
</td>
<td width="13%">
<input type="text" value="<?= $oRoute->getAction(); ?>"/>
</td>
<td width="13%">
<input type="text" class="form-actions" value="<?= $oRoute->getAccessRole(); ?>"/>
</td>
<td width="13%">
<input type="text" value="<?= $oRoute->getRoleCompareOperator(); ?>"/>
</td>
<td width="9%">
<input type="hidden" name="id" value="<?= $oRoute->getId(); ?>" />
<button type="button" class="btn btn-default btn-sm" id="route_update">Edit</button>
<div id="comment"></div>
</td>
</tr>
<?
}
} ?>
</table>
</form>
</form>
<? $this->addJs('admin/cms/route'); ?>
<script type="text/javascript">
$(document).ready(function () {
ROUTE.setSaveUrl('<?=IV_Url_Base::url( 'admin_cms_routeupdate' ); ?>');
ROUTE.init();
});
</script>
My request is, as you can see the basic features are ready...Now what I need to implement is to save the data when i change a row.
This should be needed in js without refreshing the page lots of times and if the data are saved correctly you have a fade displaying the right saving..
How do I save the data when a row is changed?

Delete the "form" tags.
Use jQuery to set onclick events on the buttons.
Use parent('tr') (parent) to retrieve row element.
Using the row element use each to iterate through td tags and save the data to some array: $('td', $row).each(function () { /* parse td element */ });
Send array to PHP script using AJAX.
Save the data in PHP script and display result to AJAX using status codes (200 - OK, 4** - ERROR)
If everything is working, use jQuery to do the animations you want.

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();
} ``

Instant Checkbox update on sql rows with ajax and jquery

Example of what I want:
Hi i want on each row to update instant the checkbox with value 1 when checked and 0 when not checked.
I've make some steps and already taken in a URL via post the values, but I see that updates only on the first row of my table. I think it must have some foreach or loop on ajax to take value to other rows?
This value will export as a URL querystring (ischeck) to an extrnal URL to take import on my function to make the sql query to update the value.
Here is the javascript that for sure want changes about loop that I haven't put on charges.php.
<script>
$(function($) {
var arr = [];
$('input.checkbox').on('change', function() {
var id = "<?php echo $charge['id'] ?>";
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $('[id^="checked-]');
arr.push(check_active);
var url = "ajax_ischeck.php?id=" + id + "&ischeked=" + check_active;
console.log("url", url);
if (this.checked) {
$.ajax({
url: url,
type: "GET",
dataType: 'html',
success: function(response) {
},
});
}
});
});
</script>
Here is the table with the input checkbox sry its little big the checkbox is down to last lines on Charges.php:
<tbody>
<?php foreach ($showcharge as $charge) { ?>
<tr>
<td><?php echo htmlspecialchars($charge['created_at']); ?></td>
<td><?php echo htmlspecialchars($charge['tasks']); ?> </td>
<th width="5%"><?php if (empty($charge['taskcharges'])) {
echo "Free";
} else {
echo htmlspecialchars($charge['taskcharges'] . "\xE2\x82\xAc");
} ?></th>
<th width="5%"><?php
if (empty($charge['payment'])) {
echo htmlspecialchars($charge['payment']);
} else {
echo htmlspecialchars($charge['payment'] . "\xE2\x82\xAc");
}
?>
</th>
<th width="5%" id="balance"><?= htmlspecialchars($charge['balance'] . "\xE2\x82\xAc") ?></th>
<th width="10%"><?php if (($charge['payment_date'] == 0000 - 00 - 00)) {
echo "";
} else {
echo htmlspecialchars($charge['payment_date']);
} ?></th>
<th width="10%"><?php echo htmlspecialchars($charge['admin']); ?></th>
<th width="15%"><?php echo htmlspecialchars($charge['comments']); ?></th>
<td class="mytd">
<form action="" method="POST">
<a href="editcharge.php?id=<?php echo $charge['id'];
echo '&custid=' . $customer['id'] ?>" class="btn btn-info " role=" button " aria-disabled=" true">Edit</a>
</form>
<form id="delete-<?php echo $charge['id'] ?>" onSubmit="return confirm('Are you sure you want to delete?')" method="post">
<input type="hidden" name="id_to_delete" value="<?php echo $charge['id'] ?>" />
<input type="submit" class="btn btn-danger" name=" delete" value="delete" />
</form>
<script>
$("#delete").submit(function() {
return confirm("Are you sure you want to delete?");
});
</script>
</td>
<th width="7%"> <input class="checkbox" type="checkbox" checked value="1" id="checked-1" name="checbox"> <label> Success </label> </input> </th>
</tr>
<?php } ?>
</tbody>
The ajax_ischeck.php that gets data from charges.php post :
<?php include('dataprocess.php'); ?>
<?php include('config/pdo_connect.php'); ?>
<?php
$id = $_GET['id'];
$ischeck = $_GET['ischeck'];
if(isset($_GET["ischeck"])){
Data::ischecked($id, $ischeck);
}
and the sql query:
public static function ischecked ($id, $ischeck)
{
$sql = "UPDATE charges SET
ischecked='$ischeck'
WHERE id=$id";
$statement = conn()->prepare($sql);
$statement->execute();
/* echo $sql;
die(); */
if (!$statement) {
echo "\nPDO::errorInfo():\n";
}
}

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.

How to get and count post variable (array) in CodeIgniter?

I have form in view (i'm using codeigniter), in the form there's an element (array) like this code below:
<table class="table table-stripped table-bordered" id="tbl-obat">
<colgroup>
<col class="con0">
<col class="con1">
<col class="con0">
<col class="con1">
<col class="con0">
</colgroup>
<thead>
<tr>
<th>No.</th>
<th>Obat</th>
<th>Dosis</th>
<th>Satuan</th>
<th>Jumlah</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div id="1">1</div>
<input type="hidden" name="kd_obat_1" id="kd_obat_1" class="kd_obat" value="02">
</td>
<td>
<input type="text" name="nama_obat_1" id="nama_obat_1" class="nama_obat input-large ui-autocomplete-input valid" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
</td>
<td>
<input type="text" name="dosis_1" id="dosis_1" class="dosis input-small valid">
</td>
<td>
<select name="satuan_1" id="satuan_1" class="satuan uniformselect valid" style="width:100px;">
<option name="-">Pilih Satuan</option>
<option value="KSKO-01">AMPUL</option>
<option value="KSKO-02">BUAH</option>
<option value="KSKO-03">BOTOL</option>
<option value="KSKO-04">BUNGKUS</option>
<option value="KSKO-05">KAPLET</option>
</select>
</td>
<td>
<input type="text" name="jumlah_1" id="jumlah_1" class="jumlah input-large valid">
</td>
</tr>
<tr>
<td>
<div id="2">2</div>
<input type="hidden" name="kd_obat_2" id="kd_obat_2" class="kd_obat" value="01">
</td>
<td>
<input type="text" name="nama_obat_2" id="nama_obat_2" class="nama_obat input-large ui-autocomplete-input valid" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
</td>
<td>
<input type="text" name="dosis_2" id="dosis_2" class="dosis input-small valid">
</td>
<td>
<select name="satuan_2" id="satuan_2" class="satuan uniformselect valid" style="width:100px;">
<option name="-">Pilih Satuan</option>
<option value="KSKO-01">AMPUL</option>
<option value="KSKO-02">BUAH</option>
<option value="KSKO-03">BOTOL</option>
<option value="KSKO-04">BUNGKUS</option>
<option value="KSKO-05">KAPLET</option>
</select>
</td>
<td>
<input type="text" name="jumlah_2" id="jumlah_2" class="jumlah input-large valid">
</td>
</tr>
</tbody>
</table>
How can i count an array and get post values in controller codeigniter? i try this code doesnt work :
foreach ($_POST as $key=>$val) {
$$key = $val;
}
$obat = array();
$i = 1;
while(${"nama_obat_".$i}) {
if(isset(${"nama_obat_".$i}) or !empty(${"nama_obat_".$i}) or ${"nama_obat_".$i} !== "")
{
$obat[$i]['kd_trans_pelayanan'] = $trans_id;
$obat[$i]['nama_obat'] = ${"nama_obat_".$i};
$obat[$i]['dosis'] = ${"dosis_".$i};
$obat[$i]['kd_sat_kecil_obat'] = ${"satuan_".$i};
$obat[$i]['qty'] = ${"jumlah_".$i};
$i++;
} else {
exit(1);
}
}
echo '<pre>';
print_r($obat);
Thanks in advance!
EDIT :
i need to count field with name 'kd_obat_x' where x = 1 to n, based on user input. i need algorithm to get how many variables posted based on user input and so on get the data. here's my complete code:
view.php
<h4>Step 3: Obat</h4>
<p>
<table class="table table-stripped table-bordered" id="tbl-obat">
<colgroup>
<col class="con0" />
<col class="con1" />
<col class="con0" />
<col class="con1" />
<col class="con0" />
</colgroup>
<thead>
<tr>
<th>No.</th>
<th>Obat</th>
<th>Dosis</th>
<th>Satuan</th>
<th>Jumlah</th>
</thead>
<tbody></tbody>
</table>
</p>
<p>
<i class="icon-plus icon-white"></i> Tambah
<i class="icon-trash icon-white"></i> Hapus
</p>
my.js
<script type="text/javascript">
// Autocomplete Obat
jQuery(function() {
var counter3 = 1;
var options = {
source: '<?php echo base_url(); ?>admin/autoCompleteObat',
minLength: 2,
focus: function( event, ui ) {
jQuery('#nama_obat_'+counter3).val(ui.item.value);
jQuery(this).closest('tr').find('input.kd_obat').val(ui.item.kd_obat);
},
select: function( event, ui ) {
//event.preventDefault();
jQuery('#nama_obat_'+counter3).val(ui.item.value);
jQuery(this).closest('tr').find('input.kd_obat').val(ui.item.kd_obat);
},
messages: {
noResults: ''
}
};
jQuery('input.nama_obat').live("keydown.autocomplete", function() {
jQuery(this).autocomplete(options);
});
var addInput = function() {
if (counter3 > 1){
jQuery('a#removeObat').removeAttr('disabled');
}
var inputHTML = '<tr><td><div id="'+counter3+'">'+counter3+'</div><input type="hidden" name="kd_obat_'+counter3+'" id="kd_obat_'+counter3+'" class="kd_obat" /></td><td><input type="text" name="nama_obat_'+counter3+'" id="nama_obat_'+counter3+'" class="nama_obat input-large" /></td><td><input type="text" name="dosis_'+counter3+'" id="dosis_'+counter3+'" class="dosis input-small" /></td><td><select name="satuan_'+counter3+'" id="satuan_'+counter3+'" class="satuan uniformselect" style="width:100px;"><option name="-">Pilih Satuan</option><?php foreach($list_satuan_kecil as $lsk) : ?><option value="<?php echo $lsk['kd_sat_kecil_obat']; ?>"><?php echo $lsk['sat_kecil_obat']; ?></option><?php endforeach; ?></select></td><td><input type="text" name="jumlah_'+counter3+'" id="jumlah_'+counter3+'" class="jumlah input-large" /></td></tr>';
jQuery(inputHTML).appendTo("table#tbl-obat tbody");
jQuery("input.nama_obat:last").focus();
jQuery('html, body').animate({
scrollTop: jQuery("input.nama_obat:last").offset().top
}, 2000);
counter3++;
};
var removeInput = function() {
counter3--;
if(counter3 == 1){
jQuery('a#removeObat').attr('disabled','disabled');
//alert("Minimal sisa 1!");
counter3++;
//console.log('Jika Counter == 1 :' + counter3);
}else{
jQuery("table#tbl-obat tbody tr:last").remove();
//console.log('Jika Counter != 1 :' + counter3);
}
jQuery("input.nama_obat:last").focus();
jQuery('html, body').animate({
scrollTop: jQuery("input.nama_obat:last").offset().top
}, 2000);
};
if (!jQuery("table#tbl-obat tbody").find("input.nama_obat").length) {
addInput();
}
jQuery("a#addObat").click(addInput);
jQuery("a#removeObat").click(removeInput);
});
</script>
admin.php (controller)
function autoCompleteObat()
{
if (isset($_REQUEST['term'])){
$q = strtolower($_GET['term']);
$output = $this->m_crud->get_obat($q);
$this->output->set_content_type('application/json')->set_output(json_encode($output));
}
}
/***MASTER PELAYANAN***/
function pelayanan($par1 = '', $par2 = '', $par3 = '')
{
if (!$this->session->userdata('logged_in') == true)
{
redirect('login');
}
if ($par1 == 'tambah') {
$trans_id = $this->m_crud->generate_transaksi();
$pelayanan['kd_trans_pelayanan'] = $trans_id;
$pelayanan['kd_rekam_medis'] = $this->input->post('kd_rekam_medis');
$pelayanan['tgl_pelayanan'] = $this->functions->convert_date_sql($this->input->post('tgl_pelayanan'));
$pelayanan['kd_jenis_layanan'] = $this->input->post('kd_jenis_layanan');
$pelayanan['kd_unit_pelayanan'] = $this->input->post('kd_unit_pelayanan');
$pelayanan['kd_puskesmas'] = 'P3271010101'; //$this->session->userdata('kd_puskesmas'); // harusnya diambil dari session
$pelayanan['kd_dokter'] = $this->input->post('kd_dokter');
$pelayanan['kd_petugas'] = $this->input->post('kd_petugas');
$pelayanan['kd_status_pasien'] = $this->input->post('kd_status_pasien'); // blm
$pelayanan['anamnesa'] = $this->input->post('anamnesa');
$pelayanan['cat_fisik'] = $this->input->post('cat_fisik');
$pelayanan['cat_dokter'] = $this->input->post('cat_dokter');
$pelayanan['kd_bed'] = $this->input->post('kd_bed');
$pelayanan['no_rujukan'] = $this->input->post('no_rujukan');
$pelayanan['tempat_rujukan'] = $this->input->post('tempat_rujukan');
// Pelayanan Obat
$obat = array();
$i = 1;
while(${"nama_obat_".$i}) {
if(isset(${"nama_obat_".$i}) or !empty(${"nama_obat_".$i}) or ${"nama_obat_".$i} !== ""){
$obat[$i]['kd_trans_pelayanan'] = $trans_id;
$obat[$i]['nama_obat'] = ${"nama_obat_".$i};
$obat[$i]['dosis'] = ${"dosis_".$i};
$obat[$i]['kd_sat_kecil_obat'] = ${"satuan_".$i};
$obat[$i]['qty'] = ${"jumlah_".$i};
/* insert db here */
$i++;
} else {
exit(1);
}
}
echo '<pre>';
print_r($obat);
}
}
and finally my model m_crud.php
function get_obat($q){
$this->db->select('kd_obat,nama_obat');
$this->db->like('nama_obat', $q);
$this->db->or_like('kd_obat', $q);
$query = $this->db->get('obat');
$results = array();
if($query->num_rows > 0){
$i = 1;
foreach ($query->result_array() as $row){
$results[$i]['label'] = $row['kd_obat'].' - '.$row['nama_obat']; //build an array
$results[$i]['value'] = htmlentities(stripslashes($row['nama_obat']));
$results[$i]['kd_obat'] = htmlentities(stripslashes($row['kd_obat']));
$i++;
}
}
return $results;
}
You can count all element with 'kd_obat_' using this code:
$count=0;
foreach($arr as $key=>$value){
$pos = strpos($key,'kd_obat_');
if($pos!==false){
$count++;
}else{
continue;
}
}
echo $count;
You can use following snippet for post values:
$this->input->post();
Count Array tuples:
$elements = count($this->input->post());
You can use input library for getting 'POST' data in codeIgniter Framework,
Please add following code in your code and you will get array in post type.
$postData = $this->input->post(); print_r($postData);exit;
Hope this will work for you.
Assuming that you want the values of nama_obat_1, nama_obat_2, nama_obat_3, etc
First of all you need to indicate an array in your name fields as follows
nama_obat[] for the first field, nama_obat[] for the second field and so on
optionally you can do it like this
nama_obat[1] for the first field, nama_obat[2] for the second field and so on
Then in your Controller if you var_dump() this $this->input->post('nama_obat')
will outputs an array of your values.
Then for the counting part, you can use PHP count() function.
If your $this->input->post('nama_obat'); is a one level array then you can use
count($this->input->post('nama_obat')); // or store it in a variable then count it
and if your array is a multilevel array like
array(
'foo' => 'bar',
'myfoo' => array('mybar'=> 'myfoo')
)
Then you can use
count($this->input->post('nama_obat'), COUNT_RECURSIVE); // or store it in a variable then count it

Fill multiple fields from click with jquery mysql

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>

Categories