I have here autocomplete script with not allowing value that not in the option list. But the problem is the script isn't working. When I tried to input, the only comes out in textbox is []. Why my script isn't working properly?
Script in Mainpage
<script>
$(function() {
$("#autocomplete").autocomplete('autocomplete.php?', { mustMatch: true });
});
function changeAutoComplete (val) {
$( "#autocomplete" ).autocomplete({
source: 'autocomplete.php?selected='+val
});
}
$('input#autocomplete').result(function(event, data, formatted) {
//$("#result").html(!data ? "No match found!" : "Selected: " + formatted);
}).keyup(function() {
$(this).search();
$(this).css("background-color", "#D6D6FF");
});
</script>
Html in Mainpage
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main" onchange="changeAutoComplete(this.value)">
<option value="" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<input id="autocomplete" />
Here's my ajax in autocomplete.php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["term"]);
$selected = $mysqli->real_escape_string($_GET["selected"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' AND cat_code='$selected' GROUP BY id ORDER BY item" );
if($sql)
{
$str = array();
while($row=mysqli_fetch_array($sql))
{
$str[] = $row['item'];
}
echo json_encode($str);
}
Related
I am using below admin pannel:
https://github.com/harsh4870/phpcoreadmin
I have below code in the form (\forms\customer_form.php) where I can see static array ( <?php $opt_arr = array("India", "Middle East", "Nepal", "South Indian"); ?>), I would like to replace this static array to be picked from the MySql database (Table name: CUSTOMER| Column_name: STATE).
Thanks in advance
<div class="form-group">
<label>State</label>
<?php $opt_arr = array("Maharashtra", "Kerala", "Madhya pradesh"); ?>
<select name="state" class="form-control selectpicker" required>
<option value=" ">Please select your state</option>
<?php
foreach ($opt_arr as $opt) {
if ($edit && $opt == $customer['state']) {
$sel = 'selected';
} else {
$sel = '';
}
echo '<option value="'.$opt.'"' . $sel . '>' . $opt . '</option>';
}
?>
</select>
</div>
You'll need to start a MySQL connection and then submit a query.
Here's a quote from W3Schools.
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
Below is an example.
<?php
// Connection Info
$host = "localhost";
$user = "myuser";
$pass = "mypass";
$db = "mydb";
// Start Connection
$link = new mysqli($host, $user, $pass, $db);
// Check Connection
if ($link->connect_error) {
// Error Handler
die("MySQL Connection Error: ".$link->connect_error);
}
// Prepare Query
$query = "SELECT 'AREA_NAME' FROM 'REIGONAL_AREA'";
// Submit Query
$result = $link->query($query);
// Check for Errors
if ($result) {
// Set counter
$i = 0;
// Set data variable
$opt_arr = [];
// Loop through data
while($current = $result->fetch_assoc()) {
$output[$i] = $current[0];
$i++;
}
?>
<!DOCUMENT html>
<html>
<head>
<!-- Header Elements Go Here -->
</head>
<body>
<div class="form-group">
<label>State</label>
<?php $opt_arr = array("Maharashtra", "Kerala", "Madhya pradesh"); ?>
<select name="state" class="form-control selectpicker" required>
<option value=" ">Please select your state</option>
<?php
foreach ($opt_arr as $opt) {
if ($edit && $opt == $customer['state']) {
$sel = 'selected';
} else {
$sel = '';
}
echo '<option value="'.$opt.'"' . $sel . '>' . $opt . '</option>';
}
?>
</select>
</div>
</body>
</html>
<?php
} else {
// Error Handler
die("MySQL Error: ".$link->error);
}
?>
Ok, so I've checked the net and the other questions on here and I'm stumped. I've tried a javascript solution from a question posted on here but I think it's not liking MySQL populating the <option>s. I'll copy all the code I've got including the javascript I have.
SCRIPT:
<script>
$(function() {
$('#groups').on('change', function() {
var val = $(this).val();
var sub = $('#sub_groups');
$('option', sub).filter(function() {
if (
$(this).attr('data-group') === val || $(this).attr('data-group') === 'SHOW'
) {
$(this).show();
} else {
$(this).hide();
}
});
});
$('#groups').trigger('change');
});
</script>
PHP 1st dropdown:
<select class="form-control" id="groups">
<?php
$sql = "SELECT BoilerBrand FROM boilerbrands";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['ID']."'>".$row['BoilerBrand']."</option>";
}
?>
</select>
PHP 2nd dropdown
<select class="form-control" id="sub_groups">
<option data-group='SHOW' value="0">Model</option>
<?php
$sql = "SELECT * FROM boilermodels";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option data-group='".$row['BoilerBrand']."' value='".$row['BoilerGC']."'>".$row['BoilerModel']."</option>";
}
?>
</select>
Any help with this would be greatly appreciated!
Thanks :)
The way I normally do this is instead of hiding/showing the options I remove/add them. I believe if you hide the options then the select input can still have that value.
SCRIPT:
<script>
$(function(){
<?php
$sql = "SELECT * FROM boilermodels";
$result = mysql_query($sql);
$models = array();
while ($row = mysql_fetch_array($result)) {
$models[$row['BoilerBrand']][] = $row;
}
/* should look like
$models = [];
$models[1][] = ['ModelID'=>'1','BoilerBrand'=>'1','BoilerModel'=>'240E','BoilerGC'=>'47-777-77','BoilerImage'=>'47-777-77.jpg' ];
$models[1][] = ['ModelID'=>'3','BoilerBrand'=>'1','BoilerModel'=>'290D','BoilerGC'=>'11-111-11','BoilerImage'=>'11-111-11.jpg' ];
$models[2][]= ['ModelID'=>'2','BoilerBrand'=>'2','BoilerModel'=>'250E','BoilerGC'=>'47-777-77','BoilerImage'=>'47-777-77.jpg' ];
*/
?>
var _boilermodels = '<?php echo json_encode($models); ?>';
var jsonBoilerModels = JSON.parse(_boilermodels);
console.log(jsonBoilerModels);
$('#groups').on('change', function(){
var $this = $(this);
var val = $this.val();
var sub = $('#sub_groups');
sub.find('option').remove();
var appendList = [];
$.each(jsonBoilerModels[val],function(key,value){
appendList.push('<option value="'.concat(value['BoilerGC'], '">', value['BoilerModel'], '</option>'));
});
sub.append(appendList);
});
$('#groups').trigger('change');
});
</script>
1st Dropdown:
<select class="form-control" id="groups">
<?php
$sql = "SELECT ID ,BoilerBrand FROM boilerbrands";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['ID']."'>".$row['BoilerBrand']."</option>";
}
?>
</select>
2nd Dropdown:
<select class="form-control" id="sub_groups">
<option value="">Select A Model</option>
</select>
I have a search box where search is done through database. In the code I have, the search is done in one input box and the dynamic search output is shown in a text area below it.
What I want is a search like Google, where when the user stars typing, it should show similar items from the db table.
For example, if I have two organizations named "Dummy 1" and "Dummy 2" and the user types in "du", the search bar should show the 2 results and user should be able to select one.
The code I have is:
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
The js is like this:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
This is the search.php file:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%$searchq%'")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
//$output = echo "<option value='".$orgname."'>" . $orgname . "</option>";
$output = $orgname;
$output2 = $orgid;
$output3 = $subs;
//$output = '<div>'.$orgname.'</div>';
}
}
}
echo ($output);
?>
How can I achieve that?
In the JS code...
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
you have given the id(#output) of a input type element to display(or to return) the HTML statements and the js script also not closed properly (syntax error).So the valid statement will be...
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
<br>
<div id="mydiv"></div>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#mydiv").html(output);
});
}
</script>
Just change your query :
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
And the query will work fine :)
Then output the response in HTML in your search.php (manage the css accordingly) :
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<div><?php echo $orgname; ?></div>';
<div><?php echo $orgid ; ?></div>';
<div><?php echo $subs ; ?></div>';
<?php
} // while
} // else
} // main if
?>
I hope this is what you required !!
Why my script doesn't work? I need to hide the sem dropdown when branch dropdown is select ALL. I try script below but it doesn't work.
And this is my script
<script>
$(document).ready(function () {
$('#branch').change(function () {
if (this.value != "ALL") {
$('#sem').show();
} else {
$('#sem').hide();
}
});
});
</script>
</head>
<body onload=showCourses(str="ALL")>
<select name="branch" id="branch" onchange="showCourses()">
<option value="ALL" selected='ALL'>ALL</option>
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT * FROM app GROUP BY app_cn ORDER BY app_cn");
while($row = $result->fetch_assoc())
{
echo '<option value="'.$row['app_cn'].'">'.$row['app_cn'].'</option>';
}?>
</select>
<select name="sem" id="sem" onchange="showCourses()">
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT * FROM app GROUP BY app_plan_no ORDER BY app_plan_no");
while($row = $result->fetch_assoc())
{
echo '<option value="'.$row['app_plan_no'].'">'.$row['app_plan_no'].'</option>';
}?>
</select>
check for this in if statement:
$('option:selected', this).val()
In this below code i have 2 dropdown in one dropdown i get course code from course subject table and in another drop relevant subject code for selected course code from course subject table should be displayed. But i cant get the dependent dropdown subject code .Pls any one help me.
Controller:student_site
function search_by_course()
{
$this->load->model('subject_model');
$id = $this->input->post('subject_id');
//get your data from model
$res_subject = $this->subject_model->subject_list($id);
$html_string = "";
$html_string .= "<select id='subject_code_id'>";
for($x=0;$x<count($res_subject);$x++)
{
$html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
}
$html_string .= "</select>";
echo json_encode(array('html_string'=>$html_string));
}
model:student_model
function subject_list($id)
{
//echo "exam_name inside get_subject_records".$exam_name;
//$this->db->select('course_code,subject_code');
//$this->db->where('exam_name',$exam_name);
$this->db->where('course_code',$course_name);
$query = $this->db->get('coursesubject');
return $query->result();
}
view:student_detail_view
<td >
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
</td>
<td>
<div class="subject"></div>
</td>
<script>
$(function(){
$("#course_code_id").live("change keypress",function(){
var id = 0;
id = $(this).val();
if( $(this).val() !==''){
$.post('<?php echo site_url('student_site/search_by_course') ?>',
{
subject_id: id
},function(data){
$(".subject").html( data['html_string']);
},"JSON"
);
}
});
});
</script>
Changes to do:
In view:
<div class="subject">
<select id="subject_code_id"></select>
</div>
<script>
$(function(){
$("#course_code_id").live("change", function(){
var id = $(this).val();
if( id != ''){
$.ajax({
url : '<?=base_url('student_site/search_by_course')?>',
type : 'POST',
data : { 'subject_id' : id },
success : function(resp){
if( resp != "" ){
$("#subject_code_id").html('resp');
}else{
alert("No response!");
}
},
error : function(resp){
alert("Error!");
}
});
}
});
});
</script>
In controller:
function search_by_course(){
$this->load->model('subject_model');
$id = $this->input->post('subject_id');
//get your data from model
$res_subject = $this->subject_model->subject_list($id);
$html_string = "";
//$html_string .= "<select id='subject_code_id'>";
for($x=0;$x<count($res_subject);$x++)
{
$html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
}
//$html_string .= "</select>";
//echo json_encode(array('html_string'=>$html_string));
echo $html_string;
}