Reviews button not working in the jquery function - javascript

I am developing a shopping website for food items. I have my products displayed on my order.php page based on an ajax call which will take the default category on my dropdown list. The items are displayed in cards each with a review button having class 'reviews'. However, when i am making a test with the button using jquery, the page is simply reloading with no action. Please help me
//order.php
<div id="message">
</div>
<div class="container" style="position:relative; top:200px; float:center">
<div class="collapse" id="filterdiv">
<form class="d-inline">
<select id="Category">
<option value='' selected>All</option>
<?php
$fCategory="SELECT DISTINCT Food_Type from food";
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$res=$conn->query($fCategory);
if($res->rowCount()>0)
{
while($row=$res->fetch(PDO::FETCH_ASSOC))
{
echo "<option value=".$conn->quote($row['Food_Type']).">".$row['Food_Type']."
</option>";
}
}
?>
</select>
<select id="price">
<option value="">Price</option>
<option value="lowtohigh">Low to High</option>
<option value="hightolow">High to Low</option>
<
</select>
</form>
</div>
<div class="row" id="result">
</div>
</div>
<script type="text/javascript" src="Bootstrap4/js/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="Bootstrap4/js/bootstrap.min.js"></script>
<!--Ajax code to get food info-->
<script type="text/javascript">
$(document).ready(function()
{
$("#filterdiv").ready(function(){
let foodType=$("#Category").val();
let price=$("#price").val();
$.ajax({
url:'action.php',
method:'post',
data:{foodType:foodType,price:price},
success:function(response)
{
$("#result").html(response);
}
});
});
});
</script>
Now for action.php
if (isset($_POST['foodType']) || isset($_POST['price']))
{
$foodType=$price=$priceSort=$foodSort="";
if (isset($_POST['foodType']))
{
$foodType=$_POST['foodType'];
if ($foodType=='')
{
$foodSort='';
}
else
{
$foodSort="WHERE Food_Type=".$conn->quote($foodType);
}
}
if (isset($_POST['price']))
{
$price=$_POST['price'];
if ($price=="lowtohigh")
{
$priceSort="ORDER BY `Food_Price(Rs)` ASC";
}
else if ($price=='hightolow')
{
$priceSort="ORDER BY `Food_Price(Rs)` DESC";
}
else
{
$priceSort="";
}
}
$foodDisp="SELECT * FROM food ".$foodSort." ".$priceSort;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$res=$conn->query($foodDisp);
while($row=$res->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="col-lg-3 mx-0">
<div class="card-deck" style="display:flex; flex:flex-wrap; padding:2px;">
<div class="card bg-transparent p-2 h-100 border-secondary mx-0 mb-2" style="min-
height:35rem;max-height:35rem;">
<img src="<?= 'foodImages/'.$row['Food_Url'] ?>" class="card-img-top img-fluid img-
responsive img-thumbnail" height="100" width="100%">
<div class="card-body p-1 text-center">
<h4 class="card-title text-center text-info"><?php echo $row['Food_Name']; ?>
</h4>
<h5 class="card-text text-center text-white"><?php echo $row['Food_Description'];
?>
</h5>
<h5 class="card-text text-center text-danger"><?php echo "Rs
".$row['Food_Price(Rs)']; ?>
</h5>
<button class="btn btn-success reviews">Reviews</button>
</div>
<div class="footer p-1">
<form action="" class="form-submit">
<input type="hidden" class="fid" value="<?php echo $row['Food_Id'] ;?>
">
<input type="hidden" class="fname" value="<?php echo $row['Food_Name'] ;?>
">
<input type="hidden" class="fprice" value="<?php echo $row['Food_Price(Rs)']
;?>
">
<input type="hidden" class="fimage" value="<?php echo $row['Food_Url'] ;?>
">
<input type="hidden" class="ftype" value="<?php echo $row['Food_Type'] ;?>
">
<button class="btn btn-info btn-block addItemBtn">Add to cart</button>
</form>
</div>
</div>
</div>
</div>
<?php }
}
?>

Change JS function:
$("form.d-inline select").on('change', function(){
let foodType=$("#Category").val();
let price=$("#price").val();
$.ajax({
url:'action.php',
method:'post',
data:{foodType:foodType,price:price},
success:function(response)
{
$("#result").html(response);
}
});
});

Related

Codeigniter javascript function keeps failing

So i'm coding a donation store inside of codeigniter. I've been working to add the cart function to it, and have made a small card that holds the items for the store, with the ability to add to cart, and a ajax request to post and reload. The thing is, in the first category, it will work fine, success and succesfully adds to cart and reloads. but if i go into the other categories and click on an item, it always returns failure.
<div class="card">
<div class="card-header p-2">
<ul class="nav nav-pills">
<?php foreach ($category as $cat) { ?>
<li class="nav-item">
<a class="nav-link" href="#<?= $cat['categ_name']; ?>" data-toggle="tab"><?= $cat['categ_name']; ?></a></li>
<? } ?>
</ul>
</div><!-- /.card-header -->
<div class="card-body">
<div class="tab-content">
<?php foreach ($category as $pane) { ?>
<div class="tab-pane" id="<?= $pane['categ_name']; ?>">
<div class="row">
<?php foreach ($item as $ditems) { ?>
<?php if ($ditems['categ_name'] == $pane['categ_name']) { ?>
<div class="col-lg-3 col-6">
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="<?= base_url() ?>assets/itemdb/<?= $ditems['image']; ?>" alt="Image" style="width:200px;height:160px;">
<h3><?= $ditems['item_name']; ?></h3>
</div>
<div class="flip-card-back">
<p><b>Price : $<?= $ditems['price']; ?></b></p>
<p><?php if ($ditems['package'] == 1) { ?>
Package Details
<?php } else { ?>
<p>Quantity : x <?= $ditems['amount']; ?></p>
<?= $ditems['descr']; ?></p>
<?php } ?>
<?php echo form_open(base_url('donation/add_cart_item'), 'class="horizontal-form" '); ?>
<div class="form-group">
<label for="quantity">Quantity:</label>
<input type="number" value="" class="form-control" id="quantity" name="quantity" placeholder="Enter Quantity">
</div>
<input type="number" value="<?= $ditems['catelog_id']; ?>" class="form-control" id="cat_id" name="cat_id" placeholder="<?= $ditems['catelog_id']; ?>" hidden>
<div class="form-group">
<button type="button" id="add_cart" class="btn" onClick="sendToCart();">Add To Cart</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
<? } ?>
<? } ?>
</div>
</div>
<? } ?>
</div>
<!-- /.tab-content -->
</div><!-- /.card-body -->
</div>
<!-- /.nav-tabs-custom -->
and this is the script im sending it to:
<?php
$url = base_url().'donation/add_cart_item';
?>
<script>
function sendToCart(){
var catId = $("#cat_id").val();
var qty = $("#quantity").val();
$.ajax({
type: "POST",
url: "<?php echo $url ?>",
data: { '<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>', cat_id: catId, quantity: qty, ajax: '1' },
dataType: "json",
cache:false,
success: function() {
location.reload();
alert("success");
},
error:function() {
alert("failure");
}
});
return false; // Stop the browser of loading the page
}
</script>
and the controller :
public function add_cart_item(){
$id = $this->input->post('cat_id');
$qty = $this->input->post('quantity');
$item = $this->cart_model->get_item($id);
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $item['price'],
'name' => $item['item_name']
);
$data = $this->security->xss_clean($data);
$insert = $this->cart->insert($data);
if ($insert) {
if ($this->input->post('ajax') != '1') {
redirect('store'); // If javascript is not enabled, reload the page with new data
} else {
echo 'true'; // If javascript is enabled, return true, so the cart gets updated
}
} else {
$this->session->set_flashdata('warning', 'Could not insert the item to cart. Please try again later or contact an Administrator with this error.');
return false;
}
You can pass this inside your sendToCart function where this refer to button which is clicked . Then , use .closest() & .find() method to get required input values and pass same to your ajax call . Also , i have added class for quantity and cat_id add that in your html as well.
Demo Code :
function sendToCart(el) {
//get closest outer div ( tabp pane ) ->find inputs with class
var catId = $(el).closest(".tab-pane").find(".cat_id").val();
var qty = $(el).closest(".tab-pane").find(".quantity").val();
console.log("ID = " + catId + " Q = " + qty)
//your ajax call..
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="card">
<div class="card-header p-2">
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="#A" data-toggle="tab">A</a></li>
<li class="nav-item">
<a class="nav-link" href="#B" data-toggle="tab">B</a></li>
</ul>
</div>
<div class="card-body">
<div class="tab-content">
<div class="tab-pane" id="A">
<div class="row">
<div class="col-lg-3 col-6">
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="<?= base_url() ?>assets/itemdb/<?= $ditems['image']; ?>" alt="Image" style="width:200px;height:160px;">
<h3>
Oil
</h3>
</div>
<div class="flip-card-back">
<p><b>Price : $134</b></p>
<p>
<p>Quantity : x 77
</p>
Soemthinhs ....
</p>
<div class="form-group">
<label for="quantity">Quantity:</label>
<!--use class here-->
<input type="number" value="" class="form-control quantity" name="quantity" placeholder="Enter Quantity">
</div>
<!--use class here-->
<input type="number" value="1" class="form-control cat_id" name="cat_id" placeholder="1" hidden>
<div class="form-group">
<!--pass this inside fn which refer to this button-->
<button type="button" id="add_cart" class="btn" onClick="sendToCart(this);">Add To Cart</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="B">
<div class="row">
<div class="col-lg-3 col-6">
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="<?= base_url() ?>assets/itemdb/<?= $ditems['image']; ?>" alt="Image" style="width:200px;height:160px;">
<h3>
Vegeatbles
</h3>
</div>
<div class="flip-card-back">
<p><b>Price : $14</b></p>
<p>
<p>Quantity : 7
</p>
Soemthinhs .... Soemthinhs ....
</p>
<div class="form-group">
<label for="quantity">Quantity:</label>
<!--use class here-->
<input type="number" value="" class="form-control quantity" name="quantity" placeholder="Enter Quantity">
</div>
<!--use class here-->
<input type="number" value="2" class="form-control cat_id" name="cat_id" placeholder="2" hidden>
<div class="form-group">
<!--pass this inside fn which refer to this button-->
<button type="button" id="add_cart" class="btn" onClick="sendToCart(this);">Add To Cart</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

what can i do to make my add to cart button work?

Please help me out, i'm working on an e-commerce site, I added a category page, on the index page the add to cart works but when I select a particular category, and I try to add any of the product, it doesn't add to the cart and it goes back to the index page, and untick the category, maybe someone can assist me here is my code below:
I have three files,
this is my index codes
index.php:
<!--= this code displays the categories -->
<h3 class="text-center text-light bg-dark p-2"><b><a style="color: white;" href="index.php">Products</a></b></h3>
`enter code here`<div class="container-fluid">
enter code here<div class="row">
<div class="col-lg-3">
<h3 class="text-center"><b>All Categories</b></h3>
<hr>
<h6 class="text-light bg-dark p-2 rounded"><b>Select Category</b></h6>
<ul class="list-group">
<?php
$sql = "SELECT DISTINCT product_cat FROM products ORDER BY product_cat";
$result = $conn->query($sql);
while ($row=$result->fetch_assoc()){
?>
<li class="list-group-item">
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input product_check" value="<?= $row['product_cat']; ?>" id="product_cat"><?= $row['product_cat']; ?>
</label>
</div>
</li>
<?php } ?>
</ul>
</div>
<div class="col-lg-9">
<h5 class="text-center" style="font-weight: bolder;" id="textChange">All Products</h5>
<hr>
<div class="text-center">
<img src="../images/loader.gif" id="loader" width="200" style="display: none;">
</div>
<div class="row" id="result">
<div id="message"></div>
<div class="row mt-2 pb-3">
<?php
include 'config.php';
$sql="SELECT * FROM products";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()):
?>
<div class="col-sm-6 col-md-3 col-lg-3 mb-2">
<div class="card-deck">
<div class="card p-2 border-secondary mb-2">
<img src="../admin/product-images/<?= $row['product_image']; ?>" class="card-img-top" height="250">
<div class="card-body p-1">
<h4 class="card-title text-center text-info"><?= $row['product_name'] ?></h4>
<h5 class="card-text text-center text-danger"><b>₦ <?= number_format($row['product_price'],2) ?>/- </b></h5>
</div>
<div class="card-footer p-1">
<form action="" class="form-submit">
<input type="hidden" class="pid" value="<?= $row['id'] ?>">
<input type="hidden" class="pname" value="<?= $row['product_name'] ?>">
<input type="hidden" class="pprice" value="<?= $row['product_price'] ?>">
<input type="hidden" class="pimage" value="<?= $row['product_image'] ?>">
<input type="hidden" class="pcode" value="<?= $row['product_code'] ?>">
<button class="btn btn-success btn-block addItemBtn"><i class="fas fa-cart-plus"></i> Add to Cart</button>
<button class="btn btn-info btn-block viewItemBtn"><i class="fas fa-info-circle"></i> View Details</button>
</form>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/dt-1.10.20/datatables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".addItemBtn").click(function(e){
e.preventDefault();
var $form = $(this).closest(".form-submit");
var pid = $form.find(".pid").val();
var pname = $form.find(".pname").val();
var pprice = $form.find(".pprice").val();
var pimage = $form.find(".pimage").val();
var pcode = $form.find(".pcode").val();
$.ajax({
url: 'action.php',
method: 'post',
data: {pid:pid,pname:pname,pprice:pprice,pimage:pimage,pcode:pcode},
success:function(response){
$("#message").html(response);
load_cart_item_number();
}
});
});
load_cart_item_number();
function load_cart_item_number(){
$.ajax({
url: '../action.php',
method: 'get',
data: {cartItem:"cart_item"},
success:function(response){
$("#cart-item").html(response);
}
});
}
$(".product_check").click(function(){
$("#loader").show();
var action = 'data';
var product_cat = get_filter_text('product_cat');
$.ajax({
url:'action.php',
method:'POST',
data:{action:action,product_cat:product_cat},
success:function(response){
$("#result").html(response);
$("#loader").hide();
$("#textChange").text("Filtered Products");
}
});
});
function get_filter_text(text_id){
var filterData = [];
$('#'+text_id+':checked').each(function(){
filterData.push($(this).val());
});
return filterData;
}
});
</script>
</body>
</html>
this is my action codes
action.php:
<?php
//db connection
require 'config.php';
//display products and category products
if (isset($_POST['action'])) {
$sql = "SELECT * FROM products WHERE product_cat !=''";
if (isset($_POST['product_cat'])) {
$product_cat = implode("','", $_POST['product_cat']);
$sql .="AND product_cat IN('".$product_cat."')";
}
$result = $conn->query($sql);
$output='';
if($result->num_rows>0){
while ($row=$result->fetch_assoc()){
$output .= '<div id="message"></div>
<div class="col-sm-6 col-md-3 col-lg-3 mb-2">
<div class="card-deck">
<div class="card p-2 border-secondary mb-2">
<img src="../admin/product-images/'.$row['product_image'].'" class="card-img-top" height="250">
<div class="card-body p-1">
<h4 class="card-title text-center text-info">'.$row['product_name'].'</h4>
<h5 class="card-text text-center text-danger"><b>₦ '.number_format($row['product_price'],2).'/- </b></h5>
</div>
<div class="card-footer p-1">
<form action="" class="form-submit">
<input type="hidden" class="pid" value="'.$row['id'].'">
<input type="hidden" class="pname" value="'.$row['product_name'].'">
<input type="hidden" class="pprice" value="'.$row['product_price'].'">
<input type="hidden" class="pimage" value="'.$row['product_image'].'">
<input type="hidden" class="pcode" value="'.$row['product_code'].'">
<button class="btn btn-success btn-block addItemBtn"><i class="fas fa-cart-
plus"></i> Add to Cart</button>
<button class="btn btn-info btn-block viewItemBtn"><i class="fas fa-info-
circle"></i> View Details</button>
</form>
</div>
</div>
</div>
</div>';
}
}
else{
$output = "<h3>No Products Found!</h3>";
}
echo $output;
}
//add to cart codes
if(isset($_POST['pid'])){
$pid = $_POST['pid'];
$pname = $_POST['pname'];
$pprice = $_POST['pprice'];
$pimage = $_POST['pimage'];
$pcode = $_POST['pcode'];
$pqty = 1;
$stmt = $conn->prepare("SELECT product_code FROM cart WHERE product_code=?");
$stmt->bind_param("s",$pcode);
$stmt->execute();
$res = $stmt->get_result();
$r = $res->fetch_assoc();
$code = $r['product_code'];
if(!$code){
$query = $conn->prepare("INSERT INTO cart (product_name,product_price,product_image,qty,total_price,product_code) VALUES (?,?,?,?,?,?)");
$query->bind_param("sssiss",$pname,$pprice,$pimage,$pqty,$pprice,$pcode);
$query->execute();
echo '<div class="alert alert-success alert-dismisible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Item added to your cart!</strong>
</div>';
}
else{
echo '<div class="alert alert-danger alert-dismisible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Item already added to your cart!</strong>
</div>';
}
}
?>
thank you

Javascript inside PHP foreach

I made a loop using foreach, to show a list of products. Then I made a modal to edit each product. I need to get the value of product dimension and I'll make a dependent drop down between 'job drop down' and 'supply drop down'. At the moment, I can't continue it with Ajax because I got a problem at the first step to get value of dimension. In this code below I tried to get 'length' value of each product through javascript. But it returns the same value, it always is the value of the first product, even if I click on the 2nd, 3rd, 4th of product in the list.
<div class="table-responsive">
<table class="table table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product</th>
<th>Supplier</th>
<th>Dimension</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
$pcs_1 = 0;
$meter_1 = 0;
foreach ($stock as $s) { ?>
<tr>
<td class="small">
<?php echo $s->cat . ' - ' . $s->prod ?>
</td>
<td class="small">
<?php echo $s->spl ?>
</td>
<td class="small">
<?php echo $s->length . ' x ' . $s->width . ' x ' . $s->height . ' x ' . $s->diameter ?>
</td>
<td>
<a type="button" data-toggle="modal" class="btn btn-small" data-target="#modal_edit<?php echo $s->id ?>"><i class="fas fa-edit"></i></a>
<!--MODAL-->
<div class="modal fade" id="modal_edit<?php echo $s->id ?>" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" method="post" action="<?php echo site_url('admin/Stock/edit/') ?>">
<div class="modal-header">
<h5 class="modal-title" id="labelModal">EDIT STOCK</h5>
</div>
<div class="modal-body">
<input type="hidden" id="length_product" class="length_product" value="<?php echo $s->length ?>" />
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<?php echo form_label('JOB') ?>
</div>
</div>
<div class="col-sm-9">
<div class="form-group">
<select name="ref" id="ref" class="form-control" required onchange="GetData()">
<option value="">-- Select Job --</option>
<?php foreach ($job as $j) : ?>
<option value="<?php echo $j->id; ?>"><?php echo $j->id ?> - <?php echo $j->cust ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<?php echo form_label('Supply') ?>
</div>
</div>
<div class="col-sm-9">
<select name="supply" id="supply" class="form-control" required>
<option value="">--Select Supply--</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-warning submitBtn">edit</button>
</div>
</form>
</div>
</div>
</div> <!-- modal -->
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
Here is the javascript :
<script type="text/javascript">
function GetData() {
var length_product = $("#length_product").val();
alert(length_product);
}
</script>
The list works well, but I don't know how to get the detail of each list on javascript (passing multiple values from 'modal inside the list' to 'Javascript').
for me it looks like that you are always getting value of
<input type="hidden" id="length_product" class="length_product" value="<?php echo $s->length ?>" />
rather than option from the select element.
Try the following:
$('#ref').on('change', function(event) {
event.preventDefault();
var length_product = $(this).val();
alert(length_product);
});
and for the PHP and HTML:
<div class="form-group">
<select name="ref" id="ref" class="form-control" required>
<option value="">-- Select Job --</option>
<?php foreach ($job as $j) { ?>
<option value="<?php echo $j["id"]; ?>"><?php echo $j["id"]; ?>-<?php echo $j["cust"]; ?></option>
<?php
}
?>
</select>
</div>
Hope this helps!

Dynamic Select box using javascript multifield in Codeigniter

Good day,
I've been trying to get all the dynamic select box but it always returning the first color.
For example i have 1 default set of color, but then i click the Add More it adds another set of color but when i posting it in my controller it always return the first color and disregard the other added set of color. This is the sample image set of color
Can someone help me on this? I've been stucked for 4days now.
Here's my view code:
<div class="form-content">
<div class="row">
<div class="col-md-12">
<p><button type="button" id="btnAdd" class="btn btn-primary">Add Color</button></p>
<br/>
</div>
</div>
<div class="row group">
<div class="col-md-5">
<div class="form-group">
<label></label>
<select name="color1[]" id="color1" class="form-control" >
<option value="" > Color 1</option>
<?php foreach($colors as $color): ?>
<option value="<?php echo $color['colorID']; ?>">
<?php echo $color['colorDesc']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label></label>
<select name="color2[]" id="color2" class="form-control" >
<option value="" > Color 2</option>
<?php foreach($colors as $color): ?>
<option value="<?php echo $color['colorID']; ?>">
<?php echo $color['colorDesc']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<button type="button" class="btn btn-danger btnRemove">X</button>
</div>
</div>
</div>
</div>
And here's the script
<script type="text/javascript">
$(".form-content").multifield({
section: ".group",
btnAdd:"#btnAdd",
btnRemove:".btnRemove",
});
</script>
And here's my Controller
$color1 = $this->input->post('color1');
$color2 = $this->input->post('color2');
for($i = 0; $i < count($color1); ++$i) {
echo $make = $color1[$i];
}
I just started using Codeigniter newbie in short. Please help me to fix this. Thanks in advance.
Try this (I not tested):
HTML:
<div class="form-content">
<div class="row">
<div class="col-md-12">
<p>
<button type="button" id="btnAdd" class="btn btn-primary">Add Color</button>
</p>
<br/>
</div>
</div>
<?php $count=0 ; if($this->input->post('color1')) $count = count($this->input->post('color1')); for($i=0;$i<$count,$i++):?>
<div class="row group">
<div class="col-md-5">
<div class="form-group">
<label></label>
<select name="color1[<?php echo $i;?>]" id="color1" class="form-control" <?php set_select( 'color1['.$i. ']',$color[ 'colorID']);?>>
<option value=""> Color 1</option>
<?php foreach($colors as $color): ?>
<option value="<?php echo $color['colorID']; ?>">
<?php echo $color[ 'colorDesc']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label></label>
<select name="color2[<?php echo $i;?>]" id="color2" class="form-control">
<option value=""> Color 2</option>
<?php foreach($colors as $color): ?>
<option value="<?php echo $color['colorID']; ?>" <?php set_select( 'color2['.$i. ']',$color[ 'colorID']);?>>
<?php echo $color[ 'colorDesc']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<button type="button" class="btn btn-danger btnRemove">X</button>
</div>
</div>
</div>
<?php endfor;?>
</div>
in controller (you can also add validation):
...
if($this->input->post('color1')) {
$result = array();
$count = count($this->input->post('color1'));
for($i=0;$i<$count;$i++) {
if($this->input->post('color1['.$i.']') && $this->input->post('color2['.$i.']')) {
$result[$i] = ['color1'=>$this->input->post('color1['.$i.']'),'color2'=>$this->input->post('color2['.$i.']')];
}
}
print_r($result);
}
...

form value disappears after reloading

when i select the color field the value selected in the sub category field disappears
here is my view page...
<div class="form-group col-md-12">
<label class="form-group col-md-3" for="exampleInputEmail1">Parent Category</label>
<div class="form-group col-md-6">
<select name="parentname" id="parentname" class="form-control">
<option value="">select one</option>
<?php foreach ($parent as $row) { ?>
<option value="<?php echo $row->id; ?>"><?php echo $row->category_name; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group col-md-12">
<label class="form-group col-md-3" for="exampleInputEmail1">Sub Category</label>
<div class="form-group col-md-6">
<select name="subname" id="subname" class="form-control">
<option value="">select one</option>
<?php foreach ($sub_cat as $row){?>
<option value="<?php echo $row->id;?>"><?php echo $row->category_name;?></option>
<?php }?>
</select>
</div>
</div>
<div class="form-group col-md-12">
<label class="form-group col-md-3" for="exampleInputEmail1">Color</label>
<div class="form-group col-md-6">
<input readonly id="mycolor" class="colorPicker evo-cp0 form-control" data-toggle="tooltip" data-placement="top" title="Pick Product color" />
</div>
</div>
<div class="form-group col-md-12">
<label for="exampleInputPassword1">Selected Colors</label>
<div class="clearfix"></div>
<div id="selected-color">
<?php if($this->session->userdata('colors')){
foreach ($this->session->userdata('colors') as $color)
{?>
<div class="col-md-2 selected-color">
<div class="color-box" style="background-color:<?php echo $color; ?>"></div>
<div class="selected-color-btn" color='<?php echo $color; ?>' data-toggle="modal" data-target="#confirm-color" >
<span class="fa fa-close" data-toggle="tooltip" data-placement="top" title="Remove color" ></span></div>
</div>
<?php }}?>
</div>
</div>
here is my js...
<script type="text/javascript">
$(document).ready(function() {
$('#mycolor').css('background-color', $('#mycolor').val());
$("#mycolor").colorpicker({});
$("#mycolor").on("change.color", function(event, color){
var url='<?php echo base_url() ?>admin_control/ajax_addProduct_color';
var product_id=$("#product_id").val();
$.post(url, {color:color,product:product_id}, function(result)
{
$('#selected-color').html(result);
location.reload();
});
});
<script>
i had sisyphus function for the values to become selected after selecting the color field but when i choose the color field the value of the subcategory field disappears

Categories