Codeigniter select box click get product details - ajax

Am creating a Billing System using Codeigniter. Here i want to select product using droupdown that product details show without refresh the page like ajax. My code is following:
View
<?php
foreach($productlists as $product)
{
?>
<tr>
<td>1</td>
<td>
<select class="form-control" name="product_id">
<option>--Select Payment--</option>
<option value="<?php echo $product['sno']; ?>"><?php echo $product['product_name']; ?></option>
</select>
</td>
<td><input type="number" name="product_order_qty" class="form-control" value="1"></td>
<td>0.8</td>
<td>0.8</td>
<td><input type="number" name="product_price" class="form-control" value="100"></td>
<td><input type="number" name="product_total" class="form-control" value="101.60"></td>
<td><a class="btn btn-primary waves-effect waves-light btn-xs"><i class="fa fa-plus"></i> Add</a></td>
</tr>
<?php } ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
//Ajax code here
</script>
And Pass the product id to controller
controller
function productdetails()
{
$id = $_GET['product_id'];
$data['product'] = $this->orders->productdetails($id);
$data['title'] = "View Customer Order";
$this->load->view('customer_order_view',$data);
}
Please help me to pass the product_id using Ajax.
Thanks in advance

<select class="form-control" name="product_id" onchange="getProduct(this.value)">
<option>--Select Payment--</option>
<option value="<?php echo $product['sno']; ?>"><?php echo $product['product_name']; ?></option>
</select>
//your jquery function
function getProduct(product_id){
alert(product_id);
$.ajax({
url: "your_url",
type: "POST",
data:
{
id:product_id,
}
}).done(function( data )
{
// alert(data);
});
}

Related

ajax only works once a refresh

I was doing a cart section where you can change your product quantity, at first i did it with a normal form, but i change it to ajax because i want to the page doesn´t need to refresh at all to show you your new quantity with your new price and your new total, so i did the following:
$('.actform').on('submit', function(ev) {
var id2 = $(this);
$.ajax({
type: $(id2).attr('method'),
url: $(id2).attr('action'),
data: $(id2).serialize(),
success: function(data) {
$('.container').load(' .container');
},
error: function() {
alert('Ha ocurrido un error');
}
});
ev.preventDefault();
});
It was all okay when you change 1 product for first time, but the second time the forms submits like it doesn´t have ajax, to fix this problem i replaced $('.container').load(' .container'); to $('.container').load(window.location.reload(false)); and it works, but i wanna know if there is another way to do it because this reload stutters a bit the page reload and it looks weird
cart.php whithout ajax (if you need to see):
<main id="main" class="main">
<?php if(!empty($_SESSION['cart'])){ ?>
<div class="container">
<h2 class="carrito-title">Mi Carrito</h2>
<div class="container2">
<div class="container-cart">
<table>
<thead>
<tr>
<th class="product-image">Imagen</th>
<th class="product-name">Producto</th>
<th class="product-price">Precio</th>
<th class="product-quantity">Cantidad (Modificar)</th>
<th class="product-total">Total</th>
<th class="product-remove">Eliminar</th>
</tr>
</thead>
<tbody>
<?php
$total= 0;
foreach($_SESSION['cart'] as $indice=>$producto){
$ID = $producto['ID'];
$select_products = $connect->prepare("SELECT * FROM `productos` WHERE id=$ID") or die('query failed');
$select_products->execute();
$list_products = $select_products->fetchAll(PDO::FETCH_ASSOC);
foreach($list_products as $product){
$nombre= $product['nombre'];
$precio= $product['precio'];
$codigo = $product['codigo'];
$imagen = "media/productos/$codigo.png";
?>
<tr>
<td class="product-image">
<img src="<?php echo $imagen?>" alt="<?php $nombre?>">
</td>
<td class="product-name">
<h2 class="name"><?php echo $nombre?></h2>
</td>
<td class="product-price"><h2 class="precio">$<?php echo number_format($precio, 0, ',', '.') ; ?></h2></td>
<td class="product-quantity">
<form action="backend/actProduct.php" method="post" class="actform" id="<?php echo $ID ?>">
<div class="cantidad">
<div class="cantidad-container">
<input type="hidden" name="id" min="1" value="<?php echo openssl_encrypt($ID,COD,KEY);?>">
<input type="number" class="nro updateCant" onchange="btnCart.click()" name="cantidadupd" value="<?php echo $producto['CANTIDAD'];?>">
<button name="btnCart" value="Update" type="submit" class="actualizar"><i class="fa-solid fa-rotate"></i></button>
</div>
</div>
</form>
</td>
<?php
$sub_total = $precio * $producto['CANTIDAD'];
$total = $total + $sub_total;
?>
<td><h2 class="subtotal">$<?php echo number_format($sub_total, 0, ',', '.'); ?></h2></td>
<td>
<form action="backend/deleteProduct.php" method="post">
<input type="hidden" name="id" value="<?php echo openssl_encrypt($ID,COD,KEY);?>">
<button class="delete" name="btnCart" type="submit" value="Remove" onclick="return confirm('Seguro que quieres eliminar este artículo?');">X</button>
</form>
</td>
</tr>
<?php
}};
?>
</tbody>
</table>
</div>
<?php if(isset($_SESSION['cart'])){ ?>
<div class="nocart">
<div class="final">
<h5 class="final-price preciofinal">Precio sin Impuestos: $<?php echo number_format($total, 0, ',', '.');?></h5>
<form action="backend/emptyCart.php" method="post" class="emptyform" id="<?php echo $ID ?>">
<input type="hidden" name="empty">
<button name="btnCart" type="submit" class ="vaciar" value="Empty" onclick="return confirm('¿Desea vaciar el carrito?');">Vaciar carrito</button>
</form>
</div>
<?php
if ($rol=='representante'){
?>
<div class="checkout">
<form action="productos.php">
<button name="btnFinCart" class="seguircomprando-btn">Seguir comprando</button>
</form>
<a class="checkout-btn" href="clientes.php">Seleccionar cliente</a>
</div>
<?php
}else{?>
<div class="checkout">
<form action="productos.php">
<button name="btnFinCart" class="seguircomprando-btn">Seguir comprando</button>
</form>
<form action="backend/fincompra.php" method="post" onsubmit="showLoad()">
<button name="btnFinCart" class ="checkout-btn" onclick="return confirm('¿Está seguro que desea finalizar la compra?');" value="Fin" >Finalizar compra</button>
</form>
</div>
<?php
}
?>
</div>
</div>
<?php }?>
</div>
<?php }else{
echo '
<div class="nosesion">
<h2 class="cartvacio">El carrito esta vacío</h2>
<a class="comprar-btn" href="productos.php">Comprar ahora</a>
</div>
';
}?>
</main>

input type hidden using onclik

I have a problem when entering data into the database, where I want to enter the province_name attribute, but what is stored in the database is the id
my code
<div class="form-group col-md-4">
<label>Province Name</label>
<select name="province_order" id="provinsi" class="form-control select2" style="width: 100%;">
<option value="0">-PILIH-</option>
<?php foreach($data->result() as $row):?>
<option value="<?php echo $row->id_prov;?>"><?php echo $row->nama_provinsi;?></option>
<?php endforeach;?>
</select>
<input type="text" name="province_order">
</div>
function myFunction() {
var x = document.getElementById("provinsi").value;
document.getElementById("klik").innerHTML = x;
}
nama_provinsi not save in database, but id save.
how to save the province__name attribute
Try this:-
<div class="form-group col-md-4">
<label>Province Name</label>
<select name="province_order" id="provinsi" class="form-control select2" style="width: 100%;">
<option value="0">-PILIH-</option>
<?php foreach($data->result() as $row):?>
<option value="<?php echo $row->id_prov;?>" province="<?php echo $row->nama_provinsi;?>" ><?php echo $row->nama_provinsi;?></option>
<?php endforeach;?>
</select>
<input type="text" name="province_order">
</div>
function myFunction() {
var x = $("#provinsi").attr('province');
//document.getElementById("klik").innerHTML = x;
}

how to get record into a dropdown list using both an input field value and another dropdown list value

i have 2 tables(login and subject table respectively). the input field has the session user's id (from login table) while the 1st drop down list holds all the classes assigned to him/her (from subject table). how can i collect all the subjects assigned to each classes into a 2nd drop down list still from the subject table using ajax if possible. Note:(Subject table has classes,subjects, staffid). below is my code:
<td class="header">TEACHER ID:</td>
<td>
<label>
<input type="text" name="staffid" class="input_txt" id="teachID" value="
<?php echo $staffDetails->staffID; ?>"></label>
</td>
<td class="header">CLASS:</td>
<td>
<select name="txtclassname" class="input_txt" id="class">
<option value="">-- Select Class --</option>
<?php
$staff = $staffDetails->staffID;
$stmt = $db->prepare("SELECT distinct className FROM subjects WHERE staffID = :sid");
$stmt->execute(array("sid"=>$staff));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value=""><?php echo $row['className']; ?></option>
<?php
}
?>
</select>
</td>
<td class="header">SUBJECTS:</td>
<td>
<!--I need all the subjects for a chosen class here-->
<select name="txtclassname" class="input_txt" id="class">
<option value="">--</option>
</select>
</td>
the modified javascript code:
<script type="text/javascript">
$(document).on('change', '#staffclass', function(){
if($(this).val() !==""){
$.ajax('get_staffSubjects.php?staffclass='+ $(this).val()).done(function(jsonOrHtml)){
var JSON = JSON.parse(jsonOrHtml);
var subjectSelect = $('#subject');
subjectSelect.html('<option value="">--Select Subject--</option>');
for(var i=0; i<json.length; i++){
subjectSelect.append('<option value="">'+json[i]+'</option>');
}
});
}
);
</script>
my server-side script (named:get_staffSubjects.php)
<?php
require_once 'myConn.php';
require_once 'session.php';
$db = getDB();
if(($_POST['staffclass']) & ($_POST['teachID']))
{
$staff = $_POST['teachID'];
$subs = $_POST['staffclass'];
$stmt = $db->prepare("SELECT * FROM subjects WHERE className=:staffclass AND staffID=:teachID");
$stmt->execute(array('id'=>$subs, 'teachID'=>$staff));
?>
<option value="">Select Subject:</option>
<?php
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value=""><?php echo $row['subName']; ?></option>
<?php
}
}
?>
Hi & welcome to stackoverflow. I'll just assume you know what to do on the server side to get the subjects, and show you how to use jquery to get them via ajax.
<td class="header">TEACHER ID:</td>
<td>
<label>
<input type="text" name="staffid" class="input_txt" id="teachID" value="<?php echo $staffDetails->staffID; ?>">
</label>
</td>
<td class="header">CLASS:</td>
<td>
<select name="txtclassname" class="input_txt" id="class">
<option value="">-- Select Class --</option>
<?php
$staff = $staffDetails->staffID;
$stmt = $db->prepare("SELECT distinct className FROM subjects WHERE staffID = :sid");
$stmt->execute(array("sid"=>$staff));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value=""><?php echo $row['className']; ?></option>
<?php
}
?>
</select>
</td>
<td class="header">SUBJECTS:</td>
<td>
<!--Notice that I've changed the name and id of this drop-down, as I expect you need those to be unique -->
<select name="txtsubject" class="input_txt" id="subject">
<option value="">--Select Subject--</option>
</select>
</td>
<script type="text/javascript">
//I'm using jquery, which is a quick solution
//NB: I don't like that the id='class', better use some other name
$(document).ready(function(){ // this ensure the code below happens after page is fully loaded
$(document).on('change', '#class', function(){
if($(this).val()!==""){
$.ajax('get_staffSubjects.php?staffclass='+ $(this).val()).done(function(html){
var subjectSelect = $('#subject');
//since html is constructed on the server side, we'll just append the response to the drop-down
subjectSelect.html(html);
});
}
});
});
</script>
Let me know if you have any questions.

creating dynamic navigation sub menu select from database using Codeigniter?

I am trying to create a menu with submenu in codeigniter using ajax I successfully created the menu but i am facing the problem while i will create a submenu. When i click the menu I check it in cosole.log its showing controller is get the details but after that i dont know why its not working. Pls any one solve this issue. thanks in advance
This is My View Area
<form action="" method="post" id="frm_submenu">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" id="selectsubmenu">
<option value="">-- Select Submenu Menu --</option>
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="form-group">
<label class="btn btn-default btn-file">
Browse <input type="file" style="display: none;">
</label>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
This is my ajax area
$("#selectmenuid").change(function() {
var selectmenuid = $(this).val();
console.log(selectmenuid);
$.ajax({
type: "POST",
data: selectmenuid,
url: "<?= base_url() ?>Admin_Creator/SelectSubmenudropdown",
success: function(data) {
$.each(data, function(i, data) {
$('#selectsubmenu').append("<option value='" + data.submenu_id + "'>" + data.submenu_name + "</option>");
});
}
});
});
This is my Controller area
public function SelectSubmenudropdown()
{
if(isset($_POST['selectmenuid']))
{
$this->output->set_content_type("application/json")->set_output(json_encode($this->Model_Creator->getSubmenu($_POST['selectmenuid'])));
}
}
This is my Model area
public function getSubmenu(){
$this->db->select('submenu_id,submenu_name');
$this->db->from('menu,submenu');
$this->db->where('submenu.menu_id=menu.menu_id');
$this->db->where('submenu.menu_id', $selectmenuid);
return $query->result_array();
}
You have to receive $selectmenuid in your model method:
public function getSubmenu($selectmenuid){
$this->db->select('submenu_id,submenu_name');
$this->db->from('menu,submenu');
$this->db->where('submenu.menu_id=menu.menu_id');
$this->db->where('submenu.menu_id', $selectmenuid);
return $query->result_array();
}

Every Dropdown list have formopen codeigniter

i want to do is every dropdown list have submit example.
every list have formopen.
this is my sample code
<?php $delete = form_open('maintenance/delete',array('name'=>'deleteCheckForm'));
$active = form_open('maintenance/active',array('name'=>'deleteCheckForm'));
$disable = form_open('maintenance/disable',array('name'=>'deleteCheckForm'));
?>
<table>
<tr>
<?php foreach($sample as $list) { ?>
<td><input type="checkbox" name="type"></td>
<td>name :<?php echo $list->name; ?></td>
<?php } ?>
</tr>
</table>
<select onchange="this.form.submit()">
<option value="<?php echo $delete; ?>">delete</option>
<option value="<?php echo $active; ?>">active</option>
<option value="<?php echo $disable; ?>">disable</option>
</select>
<?php echo form_close(); ?>
<html>
<body>
<?php echo form_open('', array('name'=>'deleteCheckForm'))?>
<table>
<?php foreach($sample as $list) { ?>
<tr>
<td><input type="checkbox" name="type"></td>
<td>name :<?php echo $list->name; ?></td>
</tr>
<?php } ?>
</table>
<select onchange="this.form.action='<?php echo site_url('maintenance')?>/'+this.value;this.form.submit()">
<option value="delete">delete</option>
<option value="active">active</option>
<option value="disable">disable</option>
</select>
<?php echo form_close(); ?>
</body>
</html>
you can try this one
first make your form outside of php tag
<form action="your_action" id="delete_frm" method="post"></form>
<form action="your_action" id="active_frm" method="post"></form>
<form action="your_action" id="diable_frm" method="post"></form>
then your select option will be like
<select id="select_form_post">
<option value="delete">delete</option>
<option value="active">active</option>
<option value="disable">disable</option>
</select>
then your script will be like
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/ 1.7.1/ jquery.min.js"></script>
<script type="text/javascript">
$("#select_form_post").change(function(){
var form_to_post=$(this).val();
if(form_to_post=="delete")
{
$("#delete_frm").submit();
}
if(form_to_post=="active")
{
$("#active_frm").submit();
}
if(form_to_post=="disable")
{
$("#disable_frm").submit();
}
});
</script>
please let me know if you need anything more.

Resources