How to attract parent_id to hidden input codeigniter/ajax - javascript

I have a select drop down on my form, of my categories from my database
Question: When I select a category from my select form, if it has a parent id
how am I able to attract that parent id to the hidden input value on my form.
Controller
<?php
class Pages extends Admin_Controller {
public function index() {
$this->load->model('admin/catalog/model_catalog_pages');
$data['page_categories'] = array();
$results = $this->model_catalog_pages->get_category();
foreach ($results as $result) {
if ($result['parent_id']) {
// If Child Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $this->model_catalog_pages->get_parent_name($result['parent_id']) .' > '. $result['name']
);
} else {
// If Parent Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $result['name']
);
}
}
$this->load->view('template/catalog/page_form_view', $data);
}
}
?>
View
<form action="" method="post" enctype="multipart/form-data" id="form-page" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" >Categories</label>
<div class="col-sm-10">
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>"><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
</div>
</div>
</form>

The way I would tackle this problem is to add a data attribute to the dropdown menu options and then use some javascript to detect if its present. Try this:
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>" <?php echo isset($category['parent_id']?'data-parent_id="'.$category['parent_id]'"':'';?>><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
The Javascript:
var dd = document.getElementById('category_select');
var hidden = document.getElementById('category_parent_id');
dd.addEventListener('change',selectParent,false);
function selectParent(){
for(var i in dd.options){
if(dd.options[i].selected == true){
if(dd.options[i].dataset.parentid){
hidden.value = dd.options[i].dataset.parentid
}else{
hidden.value = "";
}
}
}
}
selectParent();
Here is a fiddle of the javscript doing its thing, I've used type='text' input field in the fiddle to demonstrate that it works but this the code will still work with type='hidden'
http://jsfiddle.net/cpr63ajb/1/
Edit: I've tweaked the javascript so that when the page loads, it should select whatever is in the dropdown menu by default. This avoids the need of adding a dummy 'please select' option. (old JS code available here: http://jsfiddle.net/cpr63ajb).

Thanks to #Ben Broadley working now.
By his way on the option i added data-parentid and echoed parend id so looks like this now
data-parentid="<?php echo $category['parent_id'];?>
And added his script all working
<?php
class Pages extends Admin_Controller {
public function index() {
$this->load->model('admin/catalog/model_catalog_pages');
$data['page_categories'] = array();
$results = $this->model_catalog_pages->get_category();
foreach ($results as $result) {
if ($result['parent_id']) {
// If Child Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $this->model_catalog_pages->get_parent_name($result['parent_id']) .' > '. $result['name']
);
} else {
// If Parent Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $result['name']
);
}
}
$this->load->view('template/catalog/page_form_view', $data);
}
}
?>
View
<form action="" method="post" enctype="multipart/form-data" id="form-page" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" >Categories</label>
<div class="col-sm-10">
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>" data-parentid="<?php echo $category['parent_id'];?>"><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
</div>
</div>
</form>
<script type="text/javascript">
var dd = document.getElementById('category_select');
var hidden = document.getElementById('category_parent_id');
dd.addEventListener('change',function(e){
for(var i in dd.options){
if(dd.options[i].selected == true){
if(dd.options[i].dataset.parentid){
hidden.value = dd.options[i].dataset.parentid
}else{
hidden.value = "";
}
}
}
},0);
</script>

Related

How to add list items outside form in hidden field

I have 2 lists - master and category. When moving items from master list to category list I can save category list with new values but unable to save master list with removed items. I was thinking of means of reading master list into hidden field of category list but not sure how to go about. Need help with this and herewith my code:-
<select name=master[] id=master class="master" multiple="multiple" size='6'>
<?php
$file = fopen("master.csv", "r");
while (($row = fgetcsv($file, 0, ",")) !== FALSE) {
$master = $row[0];
?>
<option value="<?php echo $master;?>"><?php echo $master; ?></option>
<?php
}
?>
</select>
<form action="" method="post">
<input type=button class="master" name=b1 id=b1 value='Move >'>
<input type=button class="master" name=b2 id=b2 value='< Remove'>
<select name=category[] id=category multiple="multiple" class=master>
<?php
$file = fopen("category.csv", "r");
while (($row = fgetcsv($file, 0, ",")) !== FALSE) {
$category = $row[0];
?>
<option value="<?php echo $category;?>"><?php echo $category;?></option>
<?php
}
?>
</select>
<input type="submit" value="Save File" name="submit">
</form>
The move and remove function works so I am not including it but here is my js for writing to csv file.
<?php
if ($_POST['master']) {
$master = $_POST['master'];
foreach ($master as $key => $value) {
$result.=$value. "\n";
}
file_put_contents('master.csv',$result);
}
if ($_POST['category']) {
$category = $_POST['category'];
$categoryunique = array_unique($category);
sort($categoryunique);
foreach ($categoryunique as $key => $value) {
$result.=$value. "\n";
}
file_put_contents('category.csv',$result);
}
?>

how can I send AJAX request in OOP?

I have form like this.
<form action="Barang.php" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-md-3"
for="id_suplier">ID suplier :</label>
<div class="col-md-5">
<select class="selectpicker" title="Ketikkan ID suplier" data-width="100%" data-live-search ="true" id="id_suplier" autocomplete="off" onchange="" required>
<?php
$query = $db->query('SELECT * FROM tb_suplier');
?>
<?php
while($row = $query->fetch(PDO::FETCH_ASSOC)){ ?>
<option value="<?php echo $row['id_suplier']; ?>"><?php echo $row['id_suplier']; ?></option>
<?php
}
?>
</select>
</div>
<span class="badge badge-info" style="margin-top:10px;" id="namasup">nama suplier</span>
</div>
</form>
<script type="text/javascript">
$('#id_suplier').on('change', function() {
var id_suplier=$("#id_suplier").val();
$.ajax({
type:"POST",
url:"Barang.php",
dataType:'json',
success:function(data) {
$("#namasup").html(data.namasup);
}
});
})
</script>
And I want send the request to Barang.php, and I want to process in getSuplier(), and get name suplier to database and put the value on id=namasup. how can I process it?
And here code Barang.php
<?php
class Barang
{
function getSuplier($id){
$query = $this->db->query("SELECT nama from tb_suplier where id='$id' ");
$result=$query->fetch(PDO::FETCH_ASSOC);
return $result;
}
}
Maybe you can do this
class Barang
{
function getSuplier($id){
// your code here ....
}
}
$barang = new Barang;
$barang->getSupplier($_GET['id']);
In addition to that, Jeff is right. You are not sending your id_suplier to the server. Please send it.
I think you no need to request name from database every time you change data in selection
In my opinion you can use this code
in html
<html>
<body>
<form action="Barang.php" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-md-3"
for="id_suplier">ID suplier :</label>
<div class="col-md-5">
<select class="selectpicker" title="Ketikkan ID suplier" data-width="100%" data-live-search ="true" id="id_suplier" autocomplete="off" onchange="" required>
</select>
</div>
<span class="badge badge-info" style="margin-top:10px;" id="namasup">nama suplier</span>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function createOption(datas)
{
var html = "";
for (var i in datas){
var data = datas[i];
html = html + '<option value="'+data['id']+'">'+ data['name'] +'</option>';
}
return html;
}
$(document).ready(function() {
//get all data
$.ajax({
type:"POST",
url:"Barang.php",
type: "json",
//dataType:'json',
success:function(res) {
var datas = JSON.parse(res);
$("#id_suplier").html(createOption(datas));
//tigger change event
$('#id_suplier').change();
}
});
$('#id_suplier').on('change', function(){
//change name in span
var name = $('#id_suplier').find(":selected").text();
$("#namasup").html(name);
});
});
</script>
</body>
in php
class Barang
{
//Method for get all datas
public function getSupliers(){
//I don't have you database so I skip this part
// $query = $this->db->query("SELECT nama from tb_suplier");
// $result=$query->fetch(PDO::FETCH_ASSOC);
// return $result;
//mock data
$datas = [[
'id' => 1,
'name' => 'Test 1',
],[
'id' => 2,
'name' => 'Test 2',
],[
'id' => 3,
'name' => 'Test 3',
]];
return $datas;
}
}
$class = new Barang();
$datas = $class->getSupliers();
echo json_encode($datas);
Hope this help

unable to fetch data in multiple dropdown

I am unable to fetch the data in the second dropdown(which is depended upon the first dropdown). e.g. when we select country then the relevant state should be displayed but it doesn't. see my code.
my html
<?php
require 'dbconfig.php';
?>
<label class="control-label">Select Distict</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=dist id=dist>
<option value='' selected>Select</option>
<?Php
$ddObj = new USER($DB_con);
$table= "tbl_dist";
$sel = $ddObj->dropdowndist($table);
foreach ($sel as $val) {
echo "<option value=$val[dist_id]>$val[dist_name]</option>";
}
?>
</select>
</div>
</div>
<label class="control-label">Select Block</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=block id=block>
</select>
</div>
</div>
my jquery
<script>
$(document).ready(function() {
$('#dist').change(function(){
var dist_id=$('#dist').val();
$('#block').empty(); //remove all existing options
$.get('ddblock.php',{'dist_id':dist_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#block").append("<option value='" + value.block_id +"'>"+value.block_name+"</option>");
});
}, "json");
});
});
</script>
ddblock.php
<?Php
$dist_id=$_GET['dist_id'];
if(!intval($dist_id)){
echo "Data Error";
exit;
}
require 'class.user.php';
$ddObj = new USER($DB_con);
$table = "tbl_block";
$result = $ddObj->fetch_block($table,$dist_id);
$main = array('data'=>$result);
echo json_encode($main);
}
?>
class.user.php
public function fetch_block($table,$dist_id){
try
{
$sel = $this->db->prepare("SELECT * FROM $table WHERE block_dist_id=:dist_id");
$sel->bindValue(':dist_id', $dist_id);
$sel->execute();
$rs = $sel->setFetchMode( PDO::FETCH_ASSOC );
return $sel;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}

add to cart div refresh through Ajax

I am trying to add items in my cart through Ajax call. I tried it doing simple just with php and it works fine. But now i am trying to convert my code for php+ajax. I have an index.php page in which i am dynamically changing my content. When i click on some nav list. It redirects me to page like this: index.php?page=item&category=Shirts&s_cat_id=2&cat_id=1 where page is passed through $_GET command every time a new page is called. I have a cart button on index.php header section.I want to refresh the div whose id is named as "cart". I am failing to do this through AJAX.Here i am pasting my code. Any suggestions or help will be appreciated.
cart div
<div id="cart">
<li style="color: #515151">
<img id="cart_img" src="images/cart.png">
Cart <span class='badge' id='comparison-count'>
<?php
if(isset($_SESSION['cart'])&& !empty($_SESSION['cart']))
{
$cart_count=count($_SESSION['cart']);
echo $cart_count;
}
else {
$cart_count=0;
echo $cart_count;
}
?>
</span>
</li>
</div>
item.php
<div>
<?php
$query=mysqli_query($con,"select * from products where cat_id='$cat_id' and s_cat_id='$s_cat_id' ORDER BY product_name ASC");
if(mysqli_num_rows($query)!=0){
while($row=mysqli_fetch_assoc($query)){
?>
<div>
<input type="hidden" id="pid" value="<?php echo $row['productid'] ?>">
<h4><?php echo $row['product_name']; ?></h4>
<h4>Price<?php echo "$" . $row['product_price']; ?> </h4>
<form method="post" action="">
<input type="hidden" id="page" name="page" value="items">
<input type="hidden" id="action" name="action" value="add">
<input type="hidden" id="id" name="id" value="<?php echo $row['productid']; ?>">
<input type="hidden" id="name" name="name" value="<?php echo $row['product_name']; ?>">
<input type="hidden" id="cat_id" name="cat_id" value="<?php echo $row['cat_id']; ?>">
<input type="hidden" id="s_cat_id" name="s_cat_id" value="<?php echo $row['s_cat_id']; ?>">
<input type="hidden" id="category" name="category" value="<?php echo $cat ?>">
<td>Colors:
<select name="color" id="color">
<option selected value="choose">choose</option>
<option value="blue" id="blue">Red</option>
<option value="blue" id="blue">Blue</option>
<option value="yellow" id="yellow">Yellow</option>
<option value="green" id="green">Green</option>
</select></td>
<td>Size : <select name="size" id="size"><option selected value="Choose size">Choose</option>
<option value="XL" id="XL">XL</option>
<option value="L" id="L">L</option></select>
</td>
</div>
<input type="submit" class="add-to-cart" id="addtocart" value="Add to Cart">
</form>
</div>
</div>
add_cart.php
<?php
include ("db/db.php");
session_start();
if($_POST){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(isset($_POST['Action']) && $_POST['Action']=="add" && isset($_POST['S_cat_id']) && isset($_POST['Cat_id']) ){
$id=intval($_POST['Id']);
$size = $_POST['Size'];
$color = $_POST['Color'];
$sql="SELECT * FROM products WHERE productid={$id}";
$data = mysqli_query($con,$sql);
if (mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$index = $id." ".$color. " ".$size;
if( isset($_SESSION['cart'][$index]) && isset($_SESSION['cart'][$index]['color']) && $_SESSION['cart'][$index]['color'] == $color && isset($_SESSION['cart'][$index]['size']) && $_SESSION['cart'][$index]['size'] == $size){
$_SESSION['cart'][$index]['quantity']++;
$output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
die($output);
}else{
$_SESSION['cart'][$index] = array('quantity' => 1,'id'=> $id, 'price' => $row['product_price'], 'size' => $size, 'color' => $color, 'name' => $row['product_name']);
$output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
die($output);
}
}
else{
$message="Product ID is invalid";
$output = json_encode(array('type'=>'error', 'text' => $message));
die($output);
}
}
}
?>
Ajax
<script>
$(document).ready(function() {
$('#addtocart').click(function(e){
e.preventDefault();
var page = $("#page").val(),
action = $("#action").val(),
name= $("#name").val(),
cat_id= $("#cat_id").val(),
s_cat_id = $("#s_cat_id").val(),
id=$("#id").val(),
color=$("#color").val(),
size=$("#size").val(),
category = $("#category").val();
var proceed = true;
if(proceed){
post_data= { 'Page': page, 'Action': action,'Name': name, 'Cat_id': cat_id,'S_cat_id':s_cat_id, 'Category': category,'Id':id,'Color':color,'Size':size};
$.post('add_cart.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
//output=$('.alert-error').html(response.text);
}else{
output= $("#cart").load();
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
So, I'm assuming that your PHP code works and that the data is sent properly. I'm also assuming that your $.ajax call works. If one of these isn't true let me know.
You should be able to simply use jQuery to update the data of the div.
$("some div").html = response.text;
Or if you want to process the data before hand.
$("some div").html = process(response.text);
I am also assuming both the php and ajax codes work well...
All you need do is store the current value state of the div by saying something like
div=document.getElementById('elem_id');
oldv = div.firstChild.nodeValue;
and then appending the new result as
newv = oldv + responseMessage;
and finally saying
div.innerHTML=newv;
I believe this should work perfectly for your refresh request situation. You could adopt and adapt this idea in various conditions.
Note: I am also assuming that both the old and new values are either text/HTML contents not requiring any mathematical calculations

How to get all the value of same class by jQuery, and insert into an array and loop count is not correct in jQuery?

This is my form
<?php
$sql15 = "select * from reviewed_title";
$query15 = sqlsrv_query( $link, $sql15);
$count = 1;
while( $row = sqlsrv_fetch_array( $query15, SQLSRV_FETCH_ASSOC) ) { ?>
<div class = "title_body">
<div class = "title_top">
<div class="form-group">
<h3><?php
$title_id = $row['id'];
echo $count .". ".$row['title'];
?>
</h3>
</div>
</div>
<?php
$sql16 = "select * from item_reviewed WHERE title_id = $title_id";
$count2=1;
$query16 = sqlsrv_query( $link, $sql16);
$query17 = sqlsrv_query($link, $sql16, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
$row_num = sqlsrv_num_rows($query17);
//$row_num = 5;
while( $row2 = sqlsrv_fetch_array( $query16, SQLSRV_FETCH_ASSOC) ) { ?>
<div class = "title_bottom"
<?php if($row_num != $count2){?> style="border-bottom: 1px solid #000000;" <?php }?> >
<div class="form-group">
<input type="hidden" name="item_reviewed_id" value="<?php echo $row2['id'];?>" class="item_reviewed_id">
<div class = "title_bottom_left">
<h6> <?php echo $count.".".$count2 .". ".$row2['items'];
?></h6>
</div>
<div class= "title_bottom_center">
<label class="col-sm-2 label2" for="email">Y,N,N/A:</label>
<!--<select name="action" class="select <select_<?php echo $row2['id'];?>" id="select_<?php echo $count."".$count2;?>">-->
<select name="action" class="select" >
<option value="">Select</option>
<option value="yes">Yes</option>
</select>
</div>
<div class ="title_bottom_right">
<label class="col-sm-2 label3" for="email">Comment:</label>
<!--<textarea name="comment" class="form-control comment commentttt comment_<?php echo $row2['id'];?>>" <id="comment_<?php echo $count."".$count2;?>" placeholder="Comment"></textarea>-->
<textarea name="comment" class="form-control comment commentttt" placeholder="Comment"></textarea>
</div>
</div>
</div>
<?php $count2++;}?>
</div>
<?php $count++; }?>
Here I get 33 input fields, 33 select fields and 33 hidden fields.From table item_reviewed here i get 33 row. My jQuery code is ..
var ittem_id = new Array();
var j = 1;
$(".item_reviewed_id" ).each(function( i ) {
ittem_id[j] = $(this).val();
j++;
});
alert(j);
Here I get 1552 values. How i can get 33 values in jQuery ?
if you ve 1552 item and that loop output only 33 rows you must ve some other elements with class .item_reviewed_id in your page.
Use 2 classes to be sure you re selecting the right elements. JQuery map could be a very easy way to map your elements values
<input type="hidden" name="item_reviewed_id" value="<?php echo $row2['id'];?>" class="item_reviewed_id thisclass">
var ittem_id = $('.item_reviewed_id.thisclass').map(function(){
return $(this).val();
});
console.log(ittem_id); //this will be an array with your values!

Categories

Resources