add to cart div refresh through Ajax - javascript

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

Related

Refresh specific HTML content that retrieves data from MySQL

So i have a form that that does a simple calculation, depending on the users input. If the results is a certain value then it stores that value in a database, then it displays that value on a page. But i have to refresh the whole page for it to retrieve the latest updated value from the the database and display on the page.
I know how to write code to refresh the whole page, but in this case i only need the section where the it displays to be refreshed.
The original form to calculate
<div class="formC">
<form action="" method="post">
<label>Base Amount</label>
<input type="text" name="base"</input>
<label>Select Currency</label>
<div class="custom-select">
<span></span>
<select name="cur_name">
<option value="" selected>Choose a Base Currency</option>
<option value="EUR">EUR</option>
<option value="USD">USD</option>
</select>
</div>
<button type="submit" value="Submit">SUBMIT</button>
</form>
</div>
The form that gets the new values from the database
<div class="formC">
<form action="test.php" method="post">
<label>Base Amount</label>
<input type="text" name="base" id="new_base" value="<?php
$results = mysqli_query($con, "SELECT * FROM contents_arr ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($results)){
echo $row["new_base"];
}
?>">
<div id="load_data"></div>
<label>Select Currency</label>
<input type="text" name="cur_name" value="<?php
$results = mysqli_query($con, "SELECT * FROM gain_name_table ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($results)){
echo $row["gain_name"];
}
?>">
<button id="btn_submit" type="submit" value="Submit">SUBMIT</button>
</form>
</div>
Calculation
<?php
$base = $_POST['base'];
$value = $_POST['val'];
$selected = $_POST['cur_name'];
if ($selected == 'EUR') {
$results_eur = $base * $value;
// USD
}elseif ($selected == 'USD') {
$results_usd = $base * $value;
}
if($selected == 'EUR'){
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_eur."')";
mysqli_query($con,$sql);
}elseif($selected == 'USD'){
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_usd"')";
mysqli_query($con,$sql);
}
I managed to find the solution for this code using Ajax and jQuery:
$(document).ready(function(){
$('#btn_submit').click(function(){
var get_data = $('#new_base').val();
if($.trim(get_data) != '')
{
$.ajax({
url:"db2.php",
method:"POST",
data:{new_base:get_data},
dataType:"text",
success:function(data)
{
$('#new_base').val("");
}
});
}
});
setInterval(function(){
$('#load_data').load("fetch.php").fadeIn("slow")
}, 1000);
});
This can be done by creating a seperate php file and replacing the content on your page with the content of that other php page using javascript. This is not a full description on how to do it, just a hint on how this is done. There are plenty of resources where it is described in detail.
One place to start could be here W3Schools Ajax & Php
getData.php
header('Content-Type: application/json; charset=utf-8');
// do your php database stuff here
$data = //...
$data = json_encode($data);
echo $data;
And in your main file, you can fetch() the content of your getData.php in javascript to get the latest result and then inject the results into your div using document.getElementById('content').innerHTML = ...
Using this method, only your div refreshed, not the whole page.

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 to show the data returned from query through ajax in a drop down list?

I have one page where onClick of radio button I am calling one java script function which contains ajax , with the url of edit.php which has the query to return the array of chapters from table.
Now I get this chapters from database, but I want to show them in select tag of chapters. Which on first page loads has all the chapters and on click of the type(radio button) I want to show the chapters which are sorted type wise.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function getValue(obj) {
var value = obj.value;
$.ajax({
type: "POST",
url: 'edit.php',
data: {
"val" : value
},
dataType: 'text',
async: false,
cache: false,
success: function (result) {
var results = result;
Select chapter :
<select name="chapters">
<?php
if (count($results > 0)) {
foreach ($results as $row):?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>
<?php
endforeach;
} else {
?>
<option value="0">No data found</option>
<?php
}
?>
// window.location.reload();
}
});
}
</script>
</head>
<body>
<?php
session_start();
//echo "type" . $_SESSION["type"] . ".<br>";
$dbh = new PDO('mysql:host=localhost;dbname=airman_handbook', 'siddhi', 'siddhi');
$type = $_SESSION["type"];
?>
<form method="post" action="uploadQuestion.php" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="text"> <br><br>
Select question type : <br><br>
<div id="types">
SSgt <input name="type" type="radio" id="t2" value="1" <?= ($type == 1 ? "checked" : ""); ?>
onClick="getValue(this)">
TSgt <input name="type" onClick="getValue(this)" type="radio" id="t1"
value="2" <?= ($type == 2 ? "checked" : ""); ?>>
MSgt <input name="type" onClick="getValue(this)" type="radio" id="t3"
value="3" <?= ($type == 3 ? "checked" : ""); ?>>
</div>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="text"> <br><br>
Enter option 2 : <input name="opt2" type="text"> <br><br>
Enter option 3 : <input name="opt3" type="text"> <br><br>
Enter option 4 : <input name="opt4" type="text"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
Select chapter :
<select name="chapters">
<?php
$stmt = $dbh->prepare("SELECT * FROM chapters");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results > 0)) {
foreach ($results as $row):?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>
<?php
endforeach;
} else {
?>
<option value="0">No data found</option>
<?php
}
?>
<?php
function getChapters($type)
{
$stmt = $dbh->prepare("SELECT * FROM chapters where type = $type");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results > 0)) {
foreach ($results as $row):?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>
<?php
endforeach;
} else {
?>
<option value="0">No data found</option>
<?php
}
}
?>
</select> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
edit.php
<?php
$dbh = new PDO('mysql:host=localhost;dbname=airman_handbook', 'siddhi', 'siddhi');
$stmt = $dbh->prepare("SELECT * FROM chapters where type = :type");
$stmt->bindParam("type",$_POST['val']);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
foreach ($results as $row)
{
echo $row['title'];
}
?>
I got the result in java script variable, how can I access this in php? Or any simpler way of keeping all codes separately and make it work?
Please help thank you..
in edit.php, from the $results, make the formation that you want like below
$chapters='';
if (count($results > 0)) {
foreach($results as $row) {
$chapters.='<option value="'.$row['id'].'">'.$row['title'].'</option>';
}
} else {
$chapters.='<option value="">No data found</option>';
}
echo $chapters;
and in script, put the result in chapters html.
<script>
function getValue(obj) {
var value = obj.value;
$.ajax({
type: "POST",
url: 'edit.php',
data: {
"val" : value
},
dataType: 'text',
async: false,
cache: false,
success: function (result) {
var results = result;
$('#chapters').html(results);
}
});
}
</script>
Hope this helps :)

automatically populate text box based on select entry

Is there a way within php to get a value picked up from database automatically?
Basically, If I have a select box & I select option "Laptop-01" , is there a way within PHP to check the database for that row and then automatically pick up the serial number of Laptop-01 and populate it within the text box for the devices serial number.
At the moment I've just got two text boxes and user would need to manually enter both the product number (Laptop-01) & then the serial number.
I've currently got the following code;
PHP
<?php
$selectquery = "SELECT * FROM `loanproducts`";
$selectresult = mysqli_query($connection, $selectquery);
$selectusersquery = "SELECT * FROM `loanusers`";
$selectusersresult = mysqli_query($connection, $selectusersquery);
if (isset($_POST['editloan'])):
$loanid = $_POST["loanid"];
$username = $_POST["username"];
$product=$_POST["product"];
$product_desc=$_POST["product_desc"];
$serial=$_POST["serial"];
$date_collected=$_POST["date_collected"];
$date_return = $_POST["date_return"];
$returned = $_POST["returned"];
$edit_query="UPDATE loans SET
username = '$username',
product = '$product',
product_desc = '$product_desc',
serial = '$serial',
date_collected ='$date_collected',
date_return = '$date_return',
returned = '$returned'
WHERE loanid ='$loanid'";
$edit_result= mysqli_query($connection, $edit_query);
if ($edit_result) :
header ('location: editloan.php?confirm=Loan successfully updated');
else :
echo "<b>This didn`t work, error: </b>";
echo mysqli_error($connection);
endif;
endif;
$loanid=$_GET['loanid'];
$my_query="select * from loans where loanid=$loanid";
$result= mysqli_query($connection, $my_query);
while ($myrow = mysqli_fetch_array($result)):
$username = $myrow["username"];
$product = $myrow["product"];
$product_desc = $myrow["product_desc"];
$serial = $myrow["serial"];
$date_collected=$myrow["date_collected"];
$date_return=$myrow["date_return"];
$returned=$myrow["returned"];
endwhile;
?>
HTML
<html>
<h2 align="center">Edit Product Form</h2>
<body>
<div id="loginp"<p align="center">Edit this loan for the Coleg Sir Gar Loan System</p></div>
<form method="POST" action="editloaninfo.php">
<div id="editp"><p align="center">
<label class="labelform">Username:</label><select name="username" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectusersresult))
{ if ( $row1[1] == $username )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product:</label><select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult))
{ if ( $row1[1] == $product )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product Description:</label><input class="inputform" type="text" name="product_desc" placeholder="Product Description..." autocomplete="off" required size="18" value="<?php echo $product_desc; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Serial Number:</label><input class="inputform" type="text" name="serial" placeholder="Serial Number..." autocomplete="off" required size="18" value="<?php echo $serial; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Collected:</label><input class="inputform" type="date" name="date_collected" autocomplete="off" size="30" value="<?php echo $date_collected; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Returned:</label><input class="inputform" type="date" name="date_return" autocomplete="off" size="30" value="<?php echo $date_return; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Returned:</label><select name="returned" style="width: 150px">
<option value="Yes" <?php echo $returned === 'Yes' ? 'selected="selected"' : '' ?>>Yes</option>
<option value="No" <?php echo $returned === 'No' ? 'selected="selected"' : '' ?>>No</option>
</select></p></div>
<br>
<input type="hidden" name=loanid value= "<?php echo $loanid; ?>" >
<div id="editp"><input class="inputform" type="submit" name="editloan" value="Save Changes">
<input class="inputform" type="button" name="Cancel" value="Cancel" onClick="window.location.href='editloan.php'"></div>
</form>
</body>
</html>
</div>
Basically you want to do is :
When User select 'Laptop-01' you page must update all INPUTS with information related to user's laptop (like Serial number).This can be done by adding AJAX
Please note : This answer will give you idea about how to Populate data from data base then you can do this for any information you needed.
<form>
<select id='product_name' onchange="get_data()">
<option value='Laptop-01'>Laptop-01</option>
</select>
<input name='serial_no' id='serial_no'>
<input name='product_no' id='product_no'>
</form>
<script src="js/ajax.js"></script>
<script>
function get_data(){
//In very short what this do is :
//get values
var serial_no = document.getElementById('product_name').value;
//create an Object
var ajax = ajaxObj("POST", "yourpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
//ajax.responsetex is things you echo from script next to it
var index1 = ajax.responseText.split(",");
//index1 is array holding values
//index1[0]=$serial_no
//index1[1]=$product_no
//Now set value of your serian_no INPUT to $serial_no = index1[0];
document.getElementById('serial_no').value = index1[0];
document.getElementById('product_no').value = index1[1]
}
}
//ajax.send = POST/GET method
ajax.send("product_name="+product_name);
}
</script>
<?php
if(isset($_POST['product_name'])){
$sql = "SELECT serial_no,product_no FROM loanuser WHERE username='$username'";
$query = ($connection , $query);
while ($myrow = mysqli_fetch_array($query)){
$serial_no = $myrow["serial_no"];
$product_no = $myrow["product_no"];
}
//form a (,) separated list and echo it.
echo $serial_no.",".$product_no;
exit();
}
?>
Ajax.js
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
If you want me to add more explanation on AJAX used in this page , please add request in comment section i will edit it to more better answer

How to attract parent_id to hidden input codeigniter/ajax

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>

Categories

Resources