Upload files not working in codeigniter - javascript

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

Related

how to find cell & get cell value in html Dynamic table use for jquery or javascript?

I have dynamic table. i am try to get cell value use jquery "closest & find" option. but not response it.
this is html code part.
<td>
<div id="ctrl-qun-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-qun-row<?php echo $row; ?>" value="<?php echo $this->set_field_value('qun',"", $row); ?>" type="number" placeholder="Enter Qun" step="0.1" required="" name="row<?php echo $row ?>[qun]" class="form-control " />
</div>
</td>
i am try to script used keyup event.
$('#ctrl-qun').on('keyup', function(){
var rowtoatal =0;
var $row =$(this).closest("td");
var qun2 =parseFloat($row.find('.qun').val());
alert($("#qun2").val()); //remove after testing
});
full code https://pastebin.com/9ZKRNH3b
You need to get the closest tr where the quantity is change and using this tr we can get value for unit price and add total to sub total column.
Demo Code (Added dummy data in value attribute of inputs):
//on change of qty
$('.qtn').on('change keyup ', function() {
//getting closest tr
var elem = $(this).closest(".input-row");
//get qty value
var qty = parseFloat($(this).val());
var rowtoatal = 0;
//get unit price value
var $row = parseFloat(elem.find("td input.unit").val());
rowtoatal = qty * $row;
console.log(qty + " * " + $row + " = " + rowtoatal)
//adding total to sub_total
elem.find("td input.sub_total").val(rowtoatal)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<table class="table table-striped table-sm" data-maxrow="100" data-minrow="1">
<thead>
<tr>
<th class="bg-light"><label for="product">Product</label></th>
<th class="bg-light"><label for="qun">Qun</label></th>
<th class="bg-light"><label for="unite_price">Unite Price</label></th>
<th class="bg-light"><label for="sub_total">Sub Total</label></th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="input-row">
<td>
<div id="ctrl-product-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-product-row<?php echo $row; ?>" value="Abcd" type="text" placeholder="Enter Product" required="" name="row<?php echo $row ?>[product]" class="form-control " />
</div>
</td>
<td data="abc">
<div id="ctrl-qun-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-qun-row<?php echo $row; ?>" value="1" type="number" placeholder="Enter Qun" step="0.1" required="" name="row<?php echo $row ?>[qun]" class="form-control qtn" />
<!--addded qtn class-->
</div>
</td>
<td>
<div id="ctrl-unite_price-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-unite_price-row<?php echo $row; ?>" value="75" type="number" placeholder="Enter Unite Price" step="0.1" required="" name="row<?php echo $row ?>[unite_price]" class="form-control unit" />
<!--added unit class-->
</div>
</td>
<td>
<div id="ctrl-sub_total-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-sub_total-row<?php echo $row; ?>" value="75" type="number" placeholder="Enter Sub Total" step="0.1" required="" name="row<?php echo $row ?>[sub_total]" class="form-control sub_total" />
<!-- added sub_total class-->
</div>
</td>
<th class="text-center">
<button type="button" class="close btn-remove-table-row">×</button>
</th>
</tr>
<tr class="input-row">
<td>
<div id="ctrl-product-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-product-row<?php echo $row; ?>" value="Abc" type="text" placeholder="Enter Product" required="" name="row<?php echo $row ?>[product]" class="form-control " />
</div>
</td>
<td>
<div id="ctrl-qun-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-qun-row<?php echo $row; ?>" value="1" type="number" placeholder="Enter Qun" step="0.1" required="" name="row<?php echo $row ?>[qun]" class="form-control qtn" />
</div>
</td>
<td>
<div id="ctrl-unite_price-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-unite_price-row<?php echo $row; ?>" value="20" type="number" placeholder="Enter Unite Price" step="0.1" required="" name="row<?php echo $row ?>[unite_price]" class="form-control unit" />
</div>
</td>
<td>
<div id="ctrl-sub_total-row<?php echo $row; ?>-holder" class="">
<input id="ctrl-sub_total-row<?php echo $row; ?>" value="10" type="number" placeholder="Enter Sub Total" step="0.1" required="" name="row<?php echo $row ?>[sub_total]" class="form-control sub_total" />
</div>
</td>
<th class="text-center">
<button type="button" class="close btn-remove-table-row">×</button>
</th>
</tr>
</tbody>
</table>

How to submit all data from some forms in a div?

I want to make some forms in a div, and in this form, there is requirement that some form can add some input text like add a row in a table and in this div can add another div to add form to write data too. I'm already success to add data but it only works in a form because my button only can submit the data if I put it in a form. I'm new in using PHP, HTML, and JavaScript, so when I was writing code, i'm still in learning too and search many website to solve this but i'm just get the answer to submit only a form.
please help me, i'm very thankful for your response
<div id="myproyek">
<div id="formtrigger" class="content">
<form id="tableToModify" name="code" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<td>Create Url</td>
<td>:</td>
<td><input type="text" name="nameURL" id="nameURL" placeholder="URL"></td>
<span class="error"><?php echo $nameURLErr;?></span>
</div>
<div class="form-group">
<td>Parameter</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="key" name="key" placeholder="Key">
<span><?php echo $keyErr ?></span>
<input type="text" id="value" name="value" placeholder="Value">
<span><?php echo $valueErr ?></span>
</div>
</form>
<input type="button" onclick="addRow()" value="Create Row" />
<div>
<label><input type="radio" name="colorRadio" value="asynchronous">Asynchronous</label>
<label><input type="radio" name="colorRadio" value="synchronous">Synchronous</label>
<div class="asynchronous box " style="display: none" >
<form id="tableAscyToModify" >
<div class="form-group">
<td>Callback Url</td>
<td>:</td>
<td><input type="text" name="createurl" placeholder="Callback URL" onfocus="this.placeholder = ''" onblur="this.placeholder = 'URL'" value="<?php echo $asyncValue?>"></td>
<span><?php echo $asyncURLErr ?></span>
</div>
<div class="form-group">
<td>Format Response</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="item-code" name="createurl" placeholder="Key">
<span><?php echo $asyncKeyErr ?></span>
<input type="text" id="item-code" name="createurl" placeholder="Value">
<span><?php echo $asyncValueErr ?></span>
</div>
</form>
<input type="button" onclick="createRowAsyc()" value="Create Row" />
</div>
<div class="synchronous box " style="display: none">
<form id="tableSyncToModify" >
<div class="form-group">
<td>Format Response</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="item-code" name="createurl" placeholder="Key">
<input type="text" id="item-code" name="createurl" placeholder="Value">
</div>
</form>
<input type="button" onclick="createRowSync()" value="Create Row" />
</div>
</div>
</form>
</div>
<button name="submit" id="submit">Submit</button>
// i think button should be here because i want to submit all my form
</div>
Here is my PHP Code
<?php
// define variables and set to empty values
$nameURLErr = $keyErr = $valueErr = $asyncURLErr = $asyncKeyErr = $asyncValueErr = $syncURLErr = $syncKeyErr = $syncValueErr = "";
$nameURL = $key = $value = $asyncURL = $asyncKey = $asyncValue = $syncURL = $syncKey = $syncValue = "";
if (isset($_POST['value'])) {
if (empty($_POST["nameURL"])) {
$nameURLErr = "URL is required";
} else {
$nameURL = test_input($_POST["nameURL"]);
// check if name only contains letters and whitespace
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$nameURL)) {
$nameURLErr = "Only letters and white space allowed";
}
}
if (empty($_POST["key"])) {
$keyErr = "Key is required";
} else {
$key = test_input($_POST["key"]);
}
if (empty($_POST["value"])) {
$valueErr = "Value is required";
} else {
$value = test_input($_POST["value"]);
}
if (empty($_POST["asyncURL"])) {
$asyncURLErr = "URL is required";
} else {
$asyncURL = test_input($_POST["asyncURL"]);
// check if name only contains letters and whitespace
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$asyncURL)) {
$asyncURLErr = "Only letters and white space allowed";
}
}
if (empty($_POST["asyncKey"])) {
$asyncKeyErr = "Key is required";
} else {
$asyncKey = test_input($_POST["asyncKey"]);
}
if (empty($_POST["asyncValue"])) {
$asyncValueErr = "Value is required";
} else {
$asyncValue = test_input($_POST["asyncValue"]);
}
$fp = fopen('data.html', 'a');
$data = '<p> URL : '.$nameURL. '</p>'.
'<p>Key : ' . $key . '<br>Value : '. $value . '</p>' .
'<p>Async URL : ' . $asyncURL . '</p>' .
'<p>Key : ' . $asyncKey . '<br>Value : ' . $asyncValue . '</p>';
;
fwrite($fp, $data);
fclose($fp);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my Javascript code
function addRow () {
document.querySelector('#tableToModify').insertAdjacentHTML(
'beforeend',
`<form>
<div class="form-group">
<input type="text" name="name" value="" placeholder="Key" />
<input type="text" name="value" value="" placeholder="Value" />
<input type="button" value="-" onclick="removeRow(this)">
</div>
</form>`
)
}
function createRowAsyc() {
document.querySelector('#tableAscyToModify').insertAdjacentHTML(
'beforeend',
`<div class="form-group">
<input type="text" name="name" value="" placeholder="Key"/>
<input type="text" name="value" value="" placeholder="Value"/>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function createRowSync() {
document.querySelector('#tableSyncToModify').insertAdjacentHTML(
'beforeend',
`<div class="form-group">
<input type="text" name="name" value="" placeholder="Key"/>
<input type="text" name="value" value="" placeholder="Value"/>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function removeRow (input) {
input.parentNode.remove()
}
I expect the output is all the data is write in all the form, but if i put the button right in last div code, but there is nothing to change.
If i put button in
<form id="tableToModify">
</form>
data is submitted only in this data and successful submitted in text.html
Or do you have some suggestion, how i manage my form template
You can get your forms into one by using FormData()
Here we have a button element outside all forms, this will be our trigger to submit:
<div>
<form id="form-one">
<!-- the form -->
</form>
<form id="form-two">
<!-- the form -->
</form>
<button type="button" id="submit-data">
<span>Submit all forms!</span>
</button>
</div>
then in your JavaScript we collect all the FormData's into one "mothership" FormData by using loops, triggered by the button click
document.addEventListener('click', function()
{
let formData = new FormData(),
formOne = new FormData(document.getElementById('form-one')),
formTwo = new FormData(document.getElementById('form-two'));
for (let pair of formOne.entries())
{
formData.append(pair[0], pair[1])
}
for (let pair of formTwo.entries())
{
formData.append(pair[0], pair[1])
}
}, false)

how to send dynamic data using ajax to controller codeigniter

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 :)

Get data attribute from an array of select box

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.

Passing javascript variable to PHP using ajax but it gives error

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>&nbsp <?= (($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},

Categories