In my controller I have the code:
<?php
class Cat_cntrl extends CI_controller{
public function __construct(){
parent::__construct();
$this->load->model('cat_model');
$this->load->helper('form','url');
}
public function index(){
$get=$this->cat_model->fetchcatdata();
$data['result']=$get;
$this->load->view('cat_view',$data);
}
public function subcatselect(){
$cate=$this->input->post('cate');
$get=$this->cat_model->getsubo($cate);
$data['result']=$get;
echo json_encode(array('result'=>$data['result']));
}
}
?>
in model I've code:
<?php
class Cat_model extends CI_model{
public function fetchcatdata(){
$this->db->select()->from('cat');
$query=$this->db->get();
if($query->num_rows() > 0){
return $query->result();
}
else {
echo "error";
}
}
public function getsubo($cate){
$this->db->select($cate)->from('sub_cat');
$query=$this->db->get();
//echo $this->db->last_query();
if($query->num_rows() > 0){
return $query->result();
}
else {
echo "error";
}
}
}
In view the code i have:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <title></title>
</head>
<body>
<form method="post" action="">
<table>
<tr>
<td>Category</td>
<td><select id="cate">
<option>
None Selected
</option>
<?php foreach ($result as $value) {
?>
<option id="val">
<?php echo $value->category; ?>
</option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Sub Category</td>
<td><select id="myselect">
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="" id="sub">
</td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$('#sub').click(function(e){
e.preventDefault();
var cate=$( "#cate option:selected").val();
var url="<?php echo base_url();?>cat_cntrl/subcatselect";
$.ajax({
type:'post',
url:url,
data:{cate :cate},
success:function(response){
}
})
})
})
</script>
The problem is how to auto populate the select through ajax in this code. What to use after success function? I'm not getting exact answer from Google for my situation.
Inside your success function your just have to loop through array which you receive as response and append option to select
$("#your_select_id").append($('<option>', {
value: 'somevalue',
text: 'some text'
}));
For example something like below
dataType: "json",
success:function(response){
$.each(response.result,function(i, item){
$("#myselect").append($('<option>', {
value: item[cate],
text: item[cate]
}));
});
}
Say if your response json looks like below, below should work, you have to decide how you send data to browser and manipulate it, below one is example for your to start with, on click it creates dropdown option, same way you can implement with ajax
var response = {
result: [{
value: 'val1',
text: 'text1'
},
{
value: 'val2',
text: 'text2'
}
]
}
$('#btn').click(function() {
$.each(response.result, function(i, item) {
$('#myselect').append($('<option>', {
value: item.value,
text: item.text
}));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect"></select>
<input type="button" value="click me to create option" id="btn" />
Also value attribute is missing
<?php foreach ($result as $value):?>
<option value="<?php echo $value->category; ?>">
<?php echo $value->category; ?>
</option>
<?php endforeach;?>
Related
I would like to know, how can I pass <select> element from html to PHP file by ajax.
Here is my index.php:
<p>
<form action = "display.php" method="post" enctype="multipart/form-data">
Select:
<select name="chosenOption" id="chosenOption" style="width:100px"">
<?php
include 'dbConnection.php';
$query = $db->query("SELECT id,name FROM products");
while($row = $query->fetch_assoc())
{
echo'
<option value="'.$row['id'].'">'.$row['name'].'
</option>';
}
?>
</select>
Display : <input type="submit" name="display" value="Display">
</form>
</p>
My display.php, where i have ajax method:
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption:chosenOption},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>
And products.php, where i want to pass selected < select > element:
<?php
include 'dbConnection.php';
$chosenOption = $_POST["chosenOption"];
// Display section
$query = $db->query("SELECT cost,description FROM products_info WHERE products_id=$chosenOption);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
echo "Actual cost and description: ".$row["cost"]. " ".$row["description"]. ;
}
} else {
echo "No data";
}
?>
I expect that selected option from index.php will be pass to products.php by ajax and display the appropriate message. The current code does not work. Any idea?
You can't refer to $("#chosenOption") in display.php, because the page has been reloaded. You need to use $_POST['chosenOption'], since that was submitted by the form.
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption: <?php echo $_POST['chosenOption']; ?>},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>
I am trying to read data from database. I am not able load the sections from the database and insert sections in dependent multi select dropdown.
my view(drop_view):
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />
<script src="jquery-ui-multiselect-widget-master/src/jquery.multiselect.js"></script>
<link rel="stylesheet" href="jquery-ui-multiselect-widget-master/jquery.multiselect.css" />
</head>
<script>
$(document).ready(function() {
$("#student").change(function() {
//alert($(this).val())
$.post("http://localhost/Dropdown/index.php/Drop_control/class", {
student: $(this).val()
}, function(data) {
$("#class").html(data);
});
});
});
</script>
<script>
$(document).ready(function() {
$("#class").change(function() {
//alert($(this).val())
$.post("http://localhost/Dropdown/index.php/Drop_control/section", {
class: $(this).val()
}, function(data) {
$("#section").html(data);
});
});
});
</script>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<div id="mine">
</div>
<script type="text/javascript">
$(function() {
$('#section').multiselect({
includeSelectAllOption: false;
});
$('#btnSelected').click(function() {
var selected = $("#section option:selected");
var message = "";
selected.each(function() {
message += $(this).text() + " " + $(this).val() + "\n";
});
alert(message);
});
});
</script>
<script>
/*$(document).ready(function(){
$('#section').multiselect({
nonSelectedText: 'Select Section',
enableFiltering: true,
enableCaseInsensitiveFiltering: true,
//buttonWidth:'400px'
});
$('#table_frame').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
// url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#section option:selected').each(function(){
$(this).prop('selected', false);
});
$('#section').multiselect('refresh');
alert(data);
}
});
});
});*/
</script>
<table class="table table-bordered">
<tr>
<td>
<div align="center">Select CSV</div>
</td>
<td>
<div align="center">:</div>
</td>
<td>
<select name="selectcsv" id="student">
<option value="" selected="selected" >Select option</option>
<option value="AllStudents" >All Students</option>
<option value="Select_Specfic_class">Select_Specfic_class</option>
</select>
</td>
</tr>
<tr>
<td>
<div align="center">Class</div>
</td>
<td>
<div align="center">:</div>
</td>
<td>
<select name="class" id="class">
<option selected="selected">Select Class</option>
</select>
</td>
</tr>
<tr>
<td>
<div align="center">Section</div>
</td>
<td>
<div align="center">:</div>
</td>
<td id="table_frame">
<select id="section" multiple="multiple">
<option selected="selected">Select Section</option>
</select>//here i am getting problem
</td>
</tr>
</table>
</body>
</html>
my model(drop_model):
<?php
class Drop_model extends CI_Model
{
function __constuct()
{
parent::__constuct();
}
public function class1()
{
$this->db->select('class');
$this->db->distinct();
$res=$this->db->get('student_details');
return $res->result();
}
public function section1($class)
{
$this->db->select('section');
$this->db->where('class',$class);
$this->db->distinct();
$res=$this->db->get('student_details');
return $res->result();
}
}
my controller(Drop_control):
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Drop_control extends CI_Controller
{
public function index()
{
$this->load->view('drop_view');
}
public function class()
{
$student=$this->input->post('student');
$this->load->model('drop_model');
$user=$this->drop_model->class1();
print_r($user);
echo '<option value="" selected="selected">Select class</option>';
foreach($user as $c){
echo '<option value="'.$c->class.'">'.$c->class.'</option>';
}
}
public function section()
{
$class=$this->input->post('class');
$this->load->model('drop_model');
$usr=$this->drop_model->section1($class);
foreach($usr as $s){
echo '<option value="'.$s->section.'">'.$s->section.'</option>';
}
}
}
?>
You can't use class name as your function name in below versions (<-5.6.x). See this. Also, remove the print_r($user); from controller's class.
view code i have : file one to show data two select box second select box depand on the first select box value
<?php
$con=mysql_connect("localhost","root","root");
mysql_select_db("register",$con);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#category").change(function(){
var value=$("#category option:selected").val();
$.ajax({
type:'post',
url:'subcat.php',
data:{ kvalue : value },
datatype:'json',
success:function(data){
alert(data);
$("#response").html(data);
}
})
})
})
</script>
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>category:</td>
<td><select id="category">
<option>Select Category</option>
<?php
$query=mysql_query("select * from category");
while($row=mysql_fetch_array($query)){
?>
<option value="<?php echo $row['category'];?>"><?php echo $row['category'];?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Sub cat:</td>
<td><select >
<option >dependent dropdown</option>
<option id="response"></option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
another page for ajax call:
This page return the data in json format to first file .problem is that i have one select box there i want to get these value in my option but i m getting this value and if m going to select on then all value auto selectrd
<?php
$con=mysql_connect("localhost","root","root");
mysql_select_db("register",$con);
$val=strtolower($_POST['kvalue']);
if($val=='mobile'){
$query=mysql_query("select mobile from subcat");
while($row=mysql_fetch_array($query)){
$row[] = $r;
print json_encode($row);
echo $row['mobile']."</br>";
}
}
problem``
i want to fetch data from json in html option but i get the value but it all in selected form how can i get or select the value one which i want??
check this demo code which select option update and your your connection and query , i just set manually data for test. this is your html file
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#category").change(function () {
var value = $("#category option:selected").val();
$.ajax({
type: 'post',
url: 'subcat.php',
data: {kvalue: value},
datatype: 'json',
success: function (data) {
alert(data);
$("#response").html(data);
}
})
})
})
</script>
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>category:</td>
<td><select id="category">
<option>Select Category</option>
<option value="mobile">Mobile</option>
<option value="TV">Tv</option>
<option value="Phone">Phone</option>
</select>
</td>
</tr>
<tr>
<td>Sub cat:</td>
<td>
<select id="response">
<option>dependent dropdown</option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
and this is your subcat.php file .i set manually data for test. if you want to select depend your option data just update your query
<?php
//$con=mysql_connect("localhost","root","root");
//mysql_select_db("register",$con);
$val = strtolower($_POST['kvalue']);
if ($val == 'mobile') {
//$query=mysql_query("select mobile from subcat");
$data = array('Option1', 'Option2', 'Option3');
foreach ($data as $value => $key) {
echo '<option value="' . $value . '">' . $key . '</option>';
}
}
if you select second option value using ajax send option then update query like
//$query=mysql_query("select mobile from subcat where subcat = '$val'");
and this is my demo data so need to replace your sql data
I have database with fields branch, name, code_member, status etc.
I am trying to fetch Names in dropdown menu with branch by group mysql query. And Then Show Details Of NAME Selected In Dropdown List. But No Results are shown.
Selection Of Branch, Name And Auto Entering of Name In Search Box is working perfectly. But After That ID, Name, Branch,Code Number etc. data is not getting displayed.
There are three pages used. index.php, findName.php and searchfinal.php
Code I tried Is As Follows :
index.php :
<html>
<head>
<script type="text/javascript">
$(document).ready(function()
{
$(".branch").change(function()
{
var branch=$(this).val();
var dataString = 'branch='+ branch;
$.ajax
({
type: "POST",
url: "findName.php",
data: dataString,
cache: false,
success: function(html)
{
$(".getname").html(html);
}
});
});
});
</script>
<script>
$(document).ready(function()
{
$('#getname').change(function() {
$('#name').val($(this).val());
});
});
</script>
</head>
<body>
Branch :
<select name="branch" class="branch">
<option selected="selected">--Select Country--</option>
<?php
$sql=mysql_query("select branch from mutualbs group by branch");
while($row=mysql_fetch_array($sql))
{
$branch=$row['branch'];
echo '<option value="'.$branch.'">'.$branch.'</option>';
} ?>
</select> <br/><br/>
Name :
<select name="getname" id="getname" class="getname">
<option selected="selected">--Select Name--</option>
</select>
<br><br>
<hr>
<form method="get">
<label for="name">Name To Search :</label>
<input type="text" id="name" name="name" />
<button class="btnSearch">Search</button>
</form>
<br><br>
<table id="resultTable" style="color:#ff0000;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>MBS Number</th>
<th>Branch</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody> //** Results Are Not Getting Shown
</table>
<script src="../js/jquery-1.10.2.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script>
$jQuery(document).ready(function($) {
$('.btnSearch').click(function(){
makeAjaxRequest();
});
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'searchfinal.php',
type: 'get',
data: {name: $('input#name').val()},
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});
</script>
</body>
</html>
Till Search Button Everything working OK... But After Clicking Search Button, No Results i.e. ID, Name, Code Number, Branch And Status Shown..
Other Codes :
searchfinal.php
<?
require_once 'Connection.simple.php';
$conn = dbConnect();
if (isset($_GET['name'])) {
$data = "%".$_GET['name']."%";
$sql = "SELECT * FROM mutualbs WHERE name like ?";
$stmt = $conn->prepare($sql);
$results = $stmt->execute(array($data));
$rows = $stmt->fetchAll();
}
if(empty($rows)) {
echo "<tr>";
echo "<td colspan='4'>There were not records</td>";
echo "</tr>";
}
else {
foreach ($rows as $row) {
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['code_number']."</td>";
echo "<td>".$row['branch']."</td>";
echo "<td>".$row['status']."</td>";
echo "</tr>";
}
}
?>
Need Help....
I'm new to codeigniter and I'm really confused on how to add options to the drop down list and save the added options in the drop down list to the database. Can anyone help me with this?
My View:
<!doctype html>
<html>
<head>
<title>My Form</title>
<script src="<?php echo base_url();?>assets/js/jquery-1.11.1.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#myselect').change(function(e) {
if ($(this).val() == "addother") {
$('#addother').show();
$('#addother_input').val('');
} else {
$('#addother').hide();
}
});
$('#add').click(function() {
$.ajax({
type: "POST",
url: window.location,// use ci url here(i.e call controller)
data: { selectboxvalue: $options.val() } ///value will be sent
})
.done(function( msg ) {
$('#add').html(msg);
});
});
});
</script>
<style>
#addother {
display: none;
}
</style>
</head>
<body>
<div id="container">
<?php
$options = array(
'small' => 'Small Shirt',
'med' => 'Medium Shirt',
'large' => 'Large Shirt',
'xlarge' => 'Extra Large Shirt',
'addother' => "Add other..."
);
echo form_dropdown('shirts', $options, null, 'id="myselect"');
?>
<div id="addother">
<?php echo form_input(array('id'=>'addother_input', 'name'=>'add', 'placeholder'=>'Enter name of school...')); ?>
<input type="submit" id="add" name="submit" value="+" />
</div>
</div>
</body>
</html>
My Controller:
function add() {
$this->load->model('fruit_model');
$data['selectboxvalue'] = $this->input->post('selectboxvalue');
$res = $this->model->addItem($data);
$this->load->view('myform');
}
function drop() {
$this->load->model('getAll');
$data["opt"] = $this->fruit_model->getAll();
$this->load->view('myform');
}
My Model:
function getAll() {
$query = $this->db->get('fruits')
return $query->result();
}
function addItem($data){
$this->db->insert('fruits', $data);
return;
}
How to save the added options into the database?
I giving simple php answer....change that to ci type
html & ajax code:
<input type="text" name="selct" id="name" ><input type="submit" id="submit"/>
<div id="box"> <select name="selectbox" id="testselect"></select></div>
<script>
$('#submit').click(function(){
$.ajax({
type: "POST",
url: "some.php",// use ci url here(i.e call controller)
data: { selectboxvalue: $("#name").val() } ///value will be sent
})
.done(function( msg ) {
$('#box').html(msg);
});
});
</script>
Some.php page
database connection
insert $_post['selectboxvalue'] value in your database and fetch all values
from database and populate in select box.i think it is easy so i am not writing
the code
try this example
<?php
class Options extends CI_Controller{
function index()
{
$this->load->view('view name');
}
function create()
{
$data = array(
'name' => $this->input->post('name'),
'price' => $this->input->post('price'));
$this->data_model->addItem($data);
$this->index();
}
}
Model
<?php
class Data_model extends CI_Model {
function getAll() {
$q = $this->db->query("SELECT * FROM items");
if($q->num_rows() >0){
foreach($q->result() as $row){
$data[]=$row;
}
}
return $data;
}
function addItem($data){
$this->db->insert('items', $data);
return;
}
}
?>
View
<html><head></head><body>
<style type="text/css">
label {display: block;}
</style>
<h2>Create</h2>
<?php echo form_open('controllername/function name/'); ?>
<p>
<label for="name">Name</label><input type="text" name="name" id="name" />
</p>
<p>
<label for="name">Price</label>
<select name="price">
<option value="1">$100</option>
<option value="2">$200</option>
<option value="3">$300</option>
</select>
</p>
<p><input type="submit" value="Submit" /></p>
<?php echo form_close(); ?>
</body>
</html>