I have a form contain looping input tag that is used for adding data. the looping form is work, and the problem is i didn't know how to retrieve that looping data in controller code igniter. please help!
this is my view (form)
<form action="#" id="ap_data">
<div class="table-responsive">
<table class="table table-striped table-hover" id="mkt">
<thead>
<tr>
<th>KR</th>
<th>NP</th>
<th>KP</th>
</tr>
</thead>
<tbody>
<?php $number =0;
$id = "id";
$idkr = "idkr";
$np = "np";
$idkp = "idkp";?>
<?php foreach ($perb as $value) {
$number++; ?>
<tr>
<input type="hidden" name="<?php echo $id.$number; ?>" value="<?php echo $value->idp ?>"/>
<td>
<input type="text" placeholder="" name="<?php echo $idkr.$number; ?>" value="<?php echo $value->idkp ?>" class="form-control">
</td>
<td>
<select name="<?php echo $np.$number; ?>" class="form-control">
<option value="1">1 (AS)</option>
<option value="2">2 (Bold)</option>
<option value="3">3 (Seed)</option>
</select>
</td>
<td>
<input type="text" placeholder="" name="<?php echo $idkp.$number; ?>" value="<?php echo $value->idkp ?>" id="class="form-control">
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="form-group">
<button type="button" onclick="test_kond()" class="btn btn-success col-lg-12">Test Kond</button>
</div>
</form>
here' is my view (Ajax function)
<script type="text/javascript">
var test_kond;
$( document ).ready(function() {
test_kond = function () {
var data_ap;
data_ap = $("#ap_data").serialize();
$.ajax({
type: "POST",
url: "<?php echo site_url('HoldBotCtrl/kond_ajax')?>",
data: data_app,
success: function() {
alert(data_ap);
}
});
};
});
and here's my controller
function kond_ajax(){
$k_t = $this->Hb_model->select_kr();
$j_kr = count($kr_total);
$idkr = "idkr";
$np = "np";
$idkp ="idkp";
for ($i=1; $i <= $jj_kr ; $i++) {
$idkrr = $idkr.$i;
$npp = $np.$i;
$idkpp = $idkp.$i;
$data_ap = array(
$idkrr => $this->input->post($idkrr),
$npp => $this->input->post($npp),
$idkpp => $this->input->post($idkpp)
);
print_r($data_ap);
}
and this is result of print_r
idkr1Array ( [idkr1] => [np1] => [idkp1] => ) idkr2Array ( [idkr2] => [np2] => [idkp2] => )
the value still null, i need to get the data from $this->input->post();.
how to fix this??
I think serilize() method creates a URL encoded string where as you want to send data via POST method in ajax. You could try this way.
var test_kond;
$( document ).ready(function() {
test_kond = function () {
var data_ap;
data_ap = new FormData($("#ap_data"));
$.ajax({
type: "POST",
url: "<?php echo site_url('HoldBotCtrl/kond_ajax')?>",
data: data_app,
success: function() {
alert(data_ap);
}
});
};
});
Just try by changing field names like below:
<form action="#" id="ap_data">
<div class="table-responsive">
<table class="table table-striped table-hover" id="mkt">
<thead>
<tr>
<th>KR</th>
<th>NP</th>
<th>KP</th>
</tr>
</thead>
<tbody>
<?php $number =0;
$id = "id";
$idkr = "idkr";
$np = "np";
$idkp = "idkp";?>
<?php foreach ($perb as $value) {
$number++; ?>
<tr>
<input type="hidden" name="data[<?= $number ?>]['id']" value="<?php echo $value->idp ?>"/>
<td>
<input type="text" placeholder="" name="data[<?= $number ?>]['idkr']" value="<?php echo $value->idkp ?>" class="form-control">
</td>
<td>
<select name="data[<?= $number ?>]['np']" class="form-control">
<option value="1">1 (AS)</option>
<option value="2">2 (Bold)</option>
<option value="3">3 (Seed)</option>
</select>
</td>
<td>
<input type="text" placeholder="" name="data[<?= $number ?>]['idkp']" value="<?php echo $value->idkp ?>" id="" class="form-control">
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="form-group">
<button type="button" onclick="test_kond()" class="btn btn-success col-lg-12">Test Kond</button>
</div>
</form>
and in your controller :
function kond_ajax(){
print_r($this->input->post());
}
I hope this will help :)
Related
I have a form on my school web application where teachers are able to add scores for students and at the end of each row, the total, which is the sum of input values is automatically calculated per student.
The problem is that it output the total of all the students instead of the total of individual students on all the rows even ones with no scores added.
How do I get the unique total value for each row?
Below is my code
<?php if($class_id >= 1 && $class_id <= 4 && $student['is_secmid'] == 1){?>
<form method="post" action="<?php echo site_url('admin/examgroup/entrymarks') ?>" id="assign_form1111">
<input type="hidden" id="max_mark" value="<?php echo $subject_detail->max_marks; ?>">
<?php
if (isset($resultlist) && !empty($resultlist)) {
?>
<div class="row">
<div class="col-md-12">
<input type="hidden" name="exam_group_class_batch_exam_subject_id" value="<?php echo $exam_group_class_batch_exam_subject_id; ?>">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>C.A 1 (10.0)</th>
<th>C.A 2 (10.0)</th>
</tr>
</thead>
<tbody>
<?php if (empty($resultlist)) {
?>
<tr>
<td colspan="7" class="text-danger text-center"><?php echo $this->lang->line('no_record_found'); ?></td>
</tr>
<?php
} else {
foreach ($resultlist as $student) {
?>
<tr class="std_adm_<?php echo $student['admission_no']; ?>">
<input type="hidden" name="prev_id[<?php echo $student['exam_group_class_batch_exam_students_id'] ?>]" value="<?php echo $student['exam_group_exam_result_id'] ?>">
<input type="hidden" name="exam_group_student_id[]" value="<?php echo $student['exam_group_class_batch_exam_students_id'] ?>">
<td><?php echo $student['admission_no']; ?></td>
<td style="white-space: nowrap;"><?php echo $student['lastname'] . " " . $student['firstname']; ?></td>
<td> <input type="number" class="marksssss2 form-control" min="0" max="10" name="exam_group_student_ca1_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $student['exam_group_exam_result_get_ca1']; ?>" step="any"></td>
<td> <input type="number" class="marksssss3 form-control" min="0" max="10" name="exam_group_student_ca2_<?php echo $student['exam_group_class_batch_exam_students_id']; ?>" value="<?php echo $student['exam_group_exam_result_get_ca2']; ?>" step="any"></td>
<td> <output class="result"></output></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
<?php if ($this->rbac->hasPrivilege('exam_marks', 'can_edit')) { ?>
<button type="submit" class="allot-fees btn btn-primary btn-sm pull-right" id="load" data-loading-text="<i class='fa fa-spinner fa-spin '></i> Please Wait.."><?php echo $this->lang->line('save'); ?>
</button>
<?php } ?>
</div>
</div>
<?php } ?>
<script>
const $inputs = $('input[type="number"]')
$inputs.change(function() {
var total = 0;
var parent = $(this).closest('.row');
parent.find('input[type="number"]').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
parent.find('.result').html(total);
});
</script>
you missed class row on <tr> and you are trying to find it on closest div from javascript, and you are getting this (<div class="row">), it have all the (<input type="number").
you forget to add class to TR. Add class row on <tr> so you can get all (<input type="number") inside the tr.
because of not added class on TR you are facing issue that all total have same numbers.
I have an account form in which the all account are being pulled from my mysql database into a dropdown menu. The user selects the account from the dropdown menu then the account code field is automatically populated via the data-acc attribute. I have added a button to add more account.
It works at first set of input and select box, but not in the next one
sample screenshot
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$('select[name="account_name[]').change(function()
{
$('.account_num').val($('select[name="account_name[]"] option:selected').data('acc'));
});
</script>
<script>
$(document).ready(function(){
var i=1;
var chart_add = '<tr id="row_chart'+i+'"><td align="center"> <input type="text" name="account_code[]" class="form-control account_num" readonly></td><td><select class="form-control selectpicker" data-live-search="true" name="account_name[]" required> <option></option><?php $account = mysqli_query($conn,"SELECT chart_of_account.acoount_no, chart_of_account.account_title from chart_of_account inner join account_group_tbl on chart_of_account.account_group = account_group_tbl.account_name where account_group_tbl.account_type = 'Expense'");while($acc = mysqli_fetch_assoc($account)){$account_no = $acc['acoount_no'];$account_title = $acc['account_title'];?><option value="<?php echo $account_title; ?>" data-price="<?php echo $account_no; ?>"><?php echo $account_title ; ?> </option><?php } ?></select></td><td><button type="button" name="remove_chart" id="'+i+'" class="btn btn-danger remove_chart"><i class="fa fa-minus"></i></button></td></tr>';
$('#add').click(function(){
i++;
$('#dynamic_field').append(chart_add);
$('.selectpicker').selectpicker('render');
});
$(document).on('click', '.remove_chart', function(){
var button_id = $(this).attr("id");
$('#row_chart'+button_id+'').remove();
});
});
</script>
<div class="row">
<div class="col-md-12">
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">Report Per Office</h3>
</div>
<div class="box-body">
<div class="col-md-12">
<h4>Project Procurement Management Plan (PPMP) <hr >
</div>
<div class="col-md-1">
Office:
</div>
<div class="col-md-4">
<select class="selectpicker" data-live-search="true" name="office_from" data-width="auto" required >
<option>--Select Reponsible Office--</option>
<?php
$q = "SELECT * FROM `office_code_dept`";
$r = mysqli_query($conn,$q);
while($row = mysqli_fetch_assoc($r)){
$off_desc = $row['off_name'];
?>
<option value="<?php echo $off_desc;?>"><?php echo $off_desc; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-md-1">Year:</div>
<div class="col-md-4"><input type="number" min="1990" max="3000" name="tax_year" class="form-control" style="text-align: center;" value="<?php echo date('Y'); ?>"></div>
<div class="col-md-2"><input type="submit" name="search" value="Search" class="btn btn-primary btn-block">
</div>
<div class="col-md-12"><br></div>
</h4>
<table class="table table-bordered" id="dynamic_field">
<thead>
<tr>
<th width="7%" rowspan="2" style="text-align: center;">Code</th>
<th width="27%" rowspan="2" style="text-align: center;">General Description</th>
<th rowspan="2" width="5%"><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus"></i></button></th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">
<input type="text" name="account_code[]" class="form-control account_num" readonly>
</td>
<td>
<select class="form-control selectpicker" data-live-search="true" name="account_name[]" required>
<option></option>
<?php
$account = mysqli_query($conn,"SELECT chart_of_account.acoount_no, chart_of_account.account_title from chart_of_account inner join account_group_tbl on chart_of_account.account_group = account_group_tbl.account_name where account_group_tbl.account_type = 'Expense'");
while($acc = mysqli_fetch_assoc($account)){
$account_no = $acc['acoount_no'];
$account_title = $acc['account_title'];
?>
<option value="<?php echo $account_title; ?>" data-acc="<?php echo $account_no; ?>">
<?php echo $account_title ; ?>
</option>
<?php } ?>
</select>
</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
your .change function is not bound to the new input and select box
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$('select[name="account_name[]').change(function()
{
$('.account_num').val($('select[name="account_name[]"] option:selected').data('acc'));
});
</script>
<script>
$(document).ready(function(){
var i=1;
var chart_add = '<tr id="row_chart'+i+'"><td align="center"> <input type="text" name="account_code[]" class="form-control account_num" readonly></td><td><select class="form-control selectpicker" data-live-search="true" name="account_name[]" required> <option></option><?php $account = mysqli_query($conn,"SELECT chart_of_account.acoount_no, chart_of_account.account_title from chart_of_account inner join account_group_tbl on chart_of_account.account_group = account_group_tbl.account_name where account_group_tbl.account_type = 'Expense'");while($acc = mysqli_fetch_assoc($account)){$account_no = $acc['acoount_no'];$account_title = $acc['account_title'];?><option value="<?php echo $account_title; ?>" data-price="<?php echo $account_no; ?>"><?php echo $account_title ; ?> </option><?php } ?></select></td><td><button type="button" name="remove_chart" id="'+i+'" class="btn btn-danger remove_chart"><i class="fa fa-minus"></i></button></td></tr>';
$('#add').click(function(){
i++;
$('#dynamic_field').append(chart_add);
$('.selectpicker').selectpicker('render');
$('select[name="account_name[]').change(function()
{
$('.account_num').val($('select[name="account_name[]"] option:selected').data('acc'));
});
});
$(document).on('click', '.remove_chart', function(){
var button_id = $(this).attr("id");
$('#row_chart'+button_id+'').remove();
});
});
</script>
Something like this should work.
So I'm trying to do Ajax POST in my wordpress site which is used in checking if checkboxes are checked and getting their values to get updated on the database on click. Using the usual PHP form submit is the easiest but the fields that I'm trying to get is outside the form.
After button click, I created an alert if the data that I need is being picked up (and they are) so I can continue with the Ajax POST. However, the POST data is not showing when I inserted an alert on the second file.
Here's my code (content-orders.php):
<div class="container">
<div class="row">
<div class="col-sm-6 text-left">
<form class="form-inline" method="post">
<select id="bulk_action_stat" name="bulk_action_stat">
<option value="BA">Bulk Actions</option>
<option value="MTT">Move To Trash</option>
<option value="MP">Mark Processing</option>
<option value="MOH">Mark On-Hold</option>
<option value="MC">Mark Complete</option>
</select>
<button class="btn btn-success" type="submit" id="check-all">Filter</button>
</form>
</div>
<div class="col-sm-6 text-right">
<form class="form-inline" method="get">
<?php $statuses = wc_get_order_statuses(); ?>
<select name="orderstatus" class="custom-select mb-2 mr-sm-2 mb-sm-0">
<option value="any">-- Select Status --</option>
<?php foreach( $statuses as $skey => $status ) : ?>
<option <?php echo ( ( isset( $_GET['orderstatus'] ) && $_GET['orderstatus'] == $skey ) ? 'selected="selected"' : '' )?> value="<?php echo $skey;?>"><?php echo $status;?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Filter" />
</form>
</div>
</div>
<?php
$status_query = 'any';
if(isset( $_GET['orderstatus'] )) {
$status_query = $_GET['orderstatus'];
}
$filters = array(
'post_status' => $status_query,
'post_type' => 'shop_order',
'posts_per_page' => 200,
'paged' => 1,
'orderby' =>'modified',
'order' => 'DESC'
);
$loop = new WP_Query( $filters );
?>
<div class="row">
<div class="table-responsive">
<table class="table responstable table-striped">
<thead>
<tr>
<th><input id="checkAll" type="checkbox"></th>
<th>Order</th>
<th>Purchased</th>
<th>SKU</th>
<th>Ship To</th>
<th>Date</th>
<th>Total</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
if( !($loop->have_posts())) {
?>
<tr>
<td colspan="8" class="text-center">No data.</td>
</tr>
<?php
} else {
while ( $loop->have_posts() ) {
$loop->the_post();
$order = new WC_Order($loop->post->ID);
?>
<tr>
<td><input id="select-item" name="bulk_actions_check" type="checkbox" value="<?php echo $loop->post->ID; ?>"></td>
<td><?php echo $order->billing_first_name." ".$order->billing_last_name; ?></td>
<td>
<?php
foreach ($order->get_items() as $key => $lineItem) {
echo $lineItem['qty']." ".$lineItem['name']."<br />";
}
?>
</td>
<td><?php
foreach ($order->get_items() as $key => $SKUItem) {
$sku_handler = new WC_Product($SKUItem['product_id']);
echo $sku_handler->sku."<br />";
}
?></td>
<td><?php echo $order->get_shipping_address(); ?></td>
<td><?php explode(" ",$order->order_date); echo $order->order_date[0];?></td>
<td><?php echo "$".$order->get_total(); ?></td>
<td><?php echo $order->status; ?></td>
<td>
<form class="form-inline" method="get">
<input type="hidden" name="status_id" value="<?php echo $order->id; ?>" />
<?php if ($order->status != 'cancelled' && $order->status != 'completed') { ?>
<?php if ($order->status != 'processing') { ?>
<button class="btn btn-primary" id="processing-<?php echo $order->id; ?>" type="submit" name="update_status" value="processing"><i class="fa fa-ellipsis-h" aria-hidden="true"></i></button>
<?php }?>
<button class="btn btn-success" id="complete-<?php echo $order->id; ?>" type="submit" name="update_status" value="completed"><i class="fa fa-check" aria-hidden="true"></i></button>
<?php }?>
<button class="btn btn-info" id="view-<?php echo $order->id; ?>" type="submit" name="update_status" value="view"><i class="fa fa-eye" aria-hidden="true"></i></button>
</form>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#checkAll").click(function () {
jQuery('input:checkbox').not(this).prop('checked', this.checked);
});
jQuery('#check-all').click(function(){
var bulk_action_status = jQuery('#bulk_action_stat').val();
var checkValues = jQuery('input[name=bulk_actions_check]:checked').map(function()
{
return jQuery(this).val();
}).get();
alert(checkValues);
jQuery.ajax({
url: '<?php echo get_stylesheet_directory_uri(); ?>/test.php',
type: 'post',
data: { ids: checkValues },
success:function(data){
}
});
});
});
On test.php is just
print_r($_POST);
These 2 files are in my child theme.
I hope someone can help. Thanks!
-Eli
I'm a bellend.
The form should just have an ID and add the form ID to all the fields outside the form.
<form id="bulk_action_filter" class="form-inline" method="post">
<select id="bulk_action_stat" name="bulk_action_stat">
<option value="">Bulk Actions</option>
<option value="trash">Move To Trash</option>
<option value="processing">Mark Processing</option>
<option value="on-hold">Mark On-Hold</option>
<option value="completed">Mark Complete</option>
</select>
<input form="bulk_action_filter" type="submit" name="filter_bulk_actions" id="check-all" value="Apply"/>
</form>
<input form="bulk_action_filter" id="select-item" name="bulk_actions_check[]" type="checkbox" value="<?php echo $loop->post->ID; ?>">
I am not able to upload files in codeigniter, and i am not getting any error, i am confused as to why this is happening and I also want to upload multiple attachments once i am done with this, but somehow i am not getting any errors while executing these codes, Is there any visible error or am i missing something? I have not uploaded any files before and this is my first attempt. I am attaching the MVC codes below:
My view form is :
<!-- form start -->
<?php echo form_open_multipart('exits/manager_add_absconding/'.$id,array('name'=>'addostcstevent','id'=>'addostcstevent','method'=>'post','autocomplete'=>'on','class'=>'form-horizontal'))?>
<?php echo form_hidden(array('id'=>$row->id,'action'=>$action));?>
<div class="box-body">
<input type="hidden" name="todays_date" readonly id="todays_date" value="<?php echo date('m/d/y');?>" class="form-control col-md-10" <?php if($USER->permissions[0] != 'all') { ?> readonly <?php } ?>>
<table>
<tr>
<td>
Name
</td>
<td>
<select class="form-control" name="name">
<?php
foreach($groups as $row)
{
echo '<option value="'.$row->firstname.'">'.$row->firstname.' '.$row->lastname.'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>
Exit Type
</td>
<td>
<select class="form-control" id="security_question_1" name="exit_type">
<option name="exit_type" value="" selected>Select a option</option>
<option name="exit_type" value="Absconding">Absconding</option>
</select>
</td>
</tr>
<tr></tr>
<tr>
<td>
<label>Absconding Since</label>
</td>
<td>
<div class="date" data-date="12-02-2012" data-date-format="mm-dd-yyyy" data-date-viewmode="years">
<input placeholder="Absconding Since" class=" m-wrap col-md-8 form-control " id="enddt" type="text" name="abscondingsince" value="<?php if($row->requested_date!='') echo date("d-m-Y",$row->requested_date); ?>" required/>
</td>
</tr>
<tr>
<td>
<label>Date of contact via Phone</label>
</td>
<td>
<div class="date" data-date="12-02-2012" data-date-format="mm-dd-yyyy" data-date-viewmode="years">
<input placeholder="Date of contact via Phone" class=" m-wrap col-md-8 form-control " id="enddtt" type="text" name="dateofcontactviaphone" value="<?php if($row->requested_date!='') echo date("d-m-Y",$row->requested_date); ?>" required/>
</td>
</tr>
<td>
<label>
Response/Outcome from attempt to contact through phone
</label>
</td>
<td>
<textarea class="form-control" name="commentsphone"></textarea>
</td>
<tr>
<td>
<label>Date of contact via email</label>
</td>
<td>
<div class="date" data-date="12-02-2012" data-date-format="mm-dd-yyyy" data-date-viewmode="years">
<input placeholder="Date of contact via email" class=" m-wrap col-md-8 form-control " id="enddttt" type="text" name="dateofcontactviaemail" value="<?php if($row->requested_date!='') echo date("d-m-Y",$row->requested_date); ?>" required/>
</td>
</tr>
<td>
<label>
Response/Outcome from attempt to contact through email
</label>
</td>
<td>
<textarea class="form-control" name="commentsemail"></textarea>
</td>
<tr>
<label>Image : </label>
<input type="file" multiple="" name="images[]">
</tr>
</tr>
</table>
</div><!-- /.box-body -->
<div class="box-footer">
<?php
echo form_hidden('action',$action);
echo form_hidden('id',$id);
?>
<!--<button type="submit" class="btn btn-info pull-right" name="withdraw" style="margin:0px 10px" value="withdrawn">Withdraw Resignation</button>-->
<button type="submit" class="btn btn-info pull-right" value="upload" style="margin:0px 10px">Submit</button>
</div><!-- /.box-footer -->
</form>
My controller methods are:
private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => './uploads/',
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return $images;
}
function manager_add_absconding(){
global $SITE,$USER;
$data = array();
$data['row'] = new stdClass();
$data['row'] = $this->admin_init_elements->set_post_vals($this->input->post());
$data['offices']=$this->mod_common->get_all_offices();
$clients = currentuserclients();
$data['roles'] = $this->mod_common->get_cat_array('designation','status',"1' AND id > '0",'designation');
$data['reasons'] = $this->exit_common->get_all_reasons();
$id = $this->uri->segment(3);
//$data['roles'] = $this->exit_common->get_cat_array('designation','status',"1' AND id > '0",'designation');
get_city_state_country_array($data,array('cityid'=>$data['row']->cityid));
$data['error_message'] = '';
$data['row']->id = $this->uri->segment(3);
$data['id'] = $this->uri->segment(3);
$data['action'] = 'add';
$data['heading'] = 'Add';
$data['msg_class'] = 'sukses';
$data['path']=$path;
$post_action = $this->input->post('action');
if($post_action=='add' || $post_action =='update' ){
$post_array = $this->input->post();
$action = ($post_action == 'add')?'inserted':'updated';
//echo '<pre>';print_r($SITE);die;
$post_array['exit_type'] = 'Employee Initiated';
$data['managerid'] = $this->exit_common->get_managerids($id);
$data['error_message'] = $this->exit_common->add_new_absconding_alert($post_array,$action);
if($data['error_message'] == 'Record '.$action.' successfully'){
$data['row'] = new stdClass();
$data['row']->id = $this->uri->segment(3);
$data['row']->status = 1;
}
}
$data['grievance_types'] = $this->mod_common->get_user_allowed_leaves();
if($data['row']->id>0){
$data['action'] = 'update';
$data['heading'] = 'Edit';
$data['rows'] = $this->mod_common->get_leave_request($data['row']->id);
$clid = $data['row']->id;
$data['row']->id = $clid;
}
//$data['my_detail'] = $this->mod_common->get_my_details($USER->id);
$data['my_detail'] = $this->exit_common->get_details_profile($USER->id,'users_details','userid');
$data['my_detail']->userdetail = $this->exit_common->get_details($USER->id,'users');
get_address($data['my_detail'],ADDRESS_TYPE1,$USER->id);
$data['cities']=$this->exit_common->get_array_frontend('city');
$data['notice_period']=$this->exit_common->get_notice_period($USER);
if (!empty($_FILES['images']['name'][0])) {
if ($this->upload_files($title, $_FILES['images']) === FALSE) {
$data['error'] = $this->upload->display_errors('<div class="alert alert-danger">', '</div>');
}
}
$data['groups'] = $this->exit_common->get_all_names_by_user($USER);
$this->data['maincontent'] = $this->load->view('maincontents/manager_add_new_exit', $data,true);
$this->load->view('layout', $this->data);
}
I am trying to pass my JavaScript variable using Ajax into my PHP script but that doesn't work it given me error that it is undefined index. both codes are in different files but both of them are accessible on the main page.
Here's my script.php
<script>
function get_child_options(){
var parentID = jQuery('#parent').val();
jQuery.ajax({
url: '/**/**/**/child_categories.php',
type: 'POST',
data: {parentID : parentID},
success: function(data){
jQuery('#child').html(data);
},
error: function(){alert("Something Went Wrong with child options. ")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
</script>
And this is my php file
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/ **/core/init.php'; //Including database path stored in init.php
$parentID = (int)$_POST['parentID'];
$childQuery = "SELECT * FROM categories WHERE parent = '$parentID' ORDER BY category";
ob_start();
?>
<option value="">Select <strong>Child</strong> Category</option>
<?php while ($child = mysqli_fetch_assoc($childQuery)): ?>
<option value="<?= $child['id']; ?>"><?= $child['category']; ?></option>
<?php endwhile; ?>
<?php
echo ob_get_clean();
?>
in script the #parent is a form id i am passing to javascript using jQuery.
because of variable is not accessible PHP is not running query.
This is my products.php the main where page where this is happening
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/Online Store/core/init.php'; //Including database path stored in init.php
include 'includes/head.php'; //Including header
include 'includes/navigation.php'; //Including Navigation bar
include 'includes/script.php';
if (isset($_GET['add'])) {
$brandQuery = $db->query("SELECT * FROM brand ORDER BY brand");
$parentQuery = $db->query("SELECT * FROM categories WHERE parent = 0 ORDER BY category");
?>
<h2 class="text-center">Add A New Product</h2><hr />
<form action="products.php?add=1" method="post" enctype="multipart/form-data">
<div class="form-group col-md-3">
<label for="title">Title*:</label>
<input type="text" class="form-control" id="title" name="title" value="<?= ((isset($_POST['title']))?sanitize($_POST['title']):''); ?>" placeholder="Add a title" />
</div>
<div class="form-group col-md-3">
<label for="brand">Brand*: </label>
<select class="form-control ">
<option value="" <?= ((isset($_POST['brand']) && $_POST['brand'] == '')?' selected':''); ?> >Select Brand</option>
<?php while($brand = mysqli_fetch_assoc($brandQuery)): ?>
<option value="<?= $brand['id']; ?>" <?= ((isset($_POST['brand']) && $_POST['brand'] == $brand['id'])?' selected':''); ?> ><?= $brand['brand'] ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="parent">Parent Category*: </label>
<select class="form-control" id="parent" name="parent">
<option value="" <?= ((isset($_POST['parent']) && $_POST['parent'] == '')?' select':''); ?> >Select <strong>Parent</strong> Category</option>
<?php while($parent = mysqli_fetch_assoc($parentQuery)): ?>
<option value="<?= $parent['id']; ?>" <?= ((isset($_POST['parent']) && $_POST['parent'] == $parent['id'])?' select':''); ?> ><?= $parent['category']; ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="child">Child Category*: </label>
<select id="child" name="child" class="form-control"></select>
<?php include $_SERVER['DOCUMENT_ROOT'].'/Online Store/admin/parsers/child_categories.php'; ?>
</div>
<div class="form-group col-md-3">
<label for="price">Price*: </label>
<input type="text" id="price" name="price" class="form-control" value="<?= ((isset($_POST['price']))?sanitize($_POST['price']):''); ?>" />
</div>
<div class="form-group col-md-3">
<label for="list_price">List Price*: </label>
<input type="text" id="list_price" name="list_price" class="form-control" value="<?= ((isset($_POST['list_price']))?sanitize($_POST['list_price']):''); ?>" />
</div>
<div class="form-group col-md-3">
<label>Quantity & Sizes</label>
<button class="btn btn-default btn-info form-control" onclick="jQuery('#sizesModal').modal('toggle'); return false;">Quantity & Sizes</button>
</div>
<div class="form-group col-md-3">
<label for="sizes">Sizes & Quantity preview*: </label>
<input type="text" name="sizes" id="sizes" class="form-control" value="<?= ((isset($_POST['sizes']))?$_POST['sizes']:''); ?>" readonly/>
</div>
<div class="form-group col-md-6">
<label for="photo">Photo*: </label>
<input type="file" name="photo" id="photo" class="form-control" />
</div>
<div class="form-group col-md-6">
<label for="description">Description</label>
<textarea name="description" id="description" class="form-control" rows="6" placeholder="Description" ><?= ((isset($_POST['description']))?sanitize($_POST['description']):''); ?></textarea>
</div>
<div class="form-group pull-right">
<input type="submit" class="form-control btn btn-success" value="Add Product" />
</div>
<div class="clearfix"></div>
</form>
<?php
}else{
$sql = "SELECT * FROM products WHERE deleted = 0";
$presults = $db->query($sql);
$product = mysqli_fetch_assoc($presults);
// Featured product
if (isset($_GET['featured'])) {
$id = (int)$_GET['id'];
$featured = (int)$_GET['featured'];
$featuredSql = "UPDATE `products` SET `featured` = '$featured' WHERE `products`.`id` = '$product[id]' ";
$db->query($featuredSql);
// header('Location: products.php');
}
?>
<h2 class="text-center">Products</h2>
Add Product<div class="clearfix"></div>
<hr />
<table class="table table-bordered table-condensed table-striped">
<thead>
<th></th>
<th>Product</th>
<th>Price</th>
<th>Category</th>
<th>Featured</th>
<th>Sold</th>
</thead>
<tbody>
<?php
while($product = mysqli_fetch_assoc($presults)):
$childID = $product['categories'];
$catSql = "SELECT * FROM categories WHERE id = '$childID'";
$result = $db->query($catSql);
$child = mysqli_fetch_assoc($result);
$parentID = $child['parent'];
$pSql = "SELECT * FROM categories WHERE id = '$parentID'";
$presult = $db->query($pSql);
$parent = mysqli_fetch_assoc($presult);
$category = $parent['category'].'~'.$child['category'];
?>
<tr>
<td>
<span class= " glyphicon glyphicon-pencil"></span>
<span class= " glyphicon glyphicon-remove-sign"></span>
</td>
<td><?= $product['title']; ?></td>
<td><?= money($product['price']) ?></td>
<td><?= $category; ?></td>
<td><a href="products.php?featured=<?= (($product['featured'] == 0)?'1':'0'); ?>&id =<?= $product['id']; ?>" class=" btn btn-sx btn-default">
<span class=" glyphicon glyphicon-<?= (($product['featured'] == 1)?'minus':'plus'); ?>"></span>
</a>  <?= (($product['featured'] == 1)?'Featured':''); ?></td>
<td>0</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php
}
include 'includes/footer.php'; //Including footer
?>
Is there any other way to do it? What I am trying to do is when user selects parent category I want child category to arrange as per parent category.
Try this:
<script>
function get_child_options(){
var parentID = $(this).val();
jQuery.ajax({
url: '/**/**/**/child_categories.php',
type: 'POST',
data: {'parentID' : parentID},
success: function(data){
jQuery('#child').html(data);
},
error: function(){alert("Something Went Wrong with child options. ")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
</script>
Getting the Value by $(this) and putting single quotes around parentID data: {'parentID' : parentID},