How to handle large data in drop down with search box bootstrap - php

I have one bootstrap drop down with search text box in my web page. I am adding dynamic data into that drop down, but they are large and come from a database. That why it takes long to load. Does anyone know the solution for this problem?
<select data-live-search="true" name="paymentfacility" id="paymentfacility" data-live-search-style="startsWith" class="selectpicker">
<?php
foreach($facilitiesall as $val)
{?>
<option value="<?php echo $val['Facility']['id']; ?>">
<?php echo $val['Facility']['name']; ?>
</option>
<?php } ?>
</select>

If you don't mind to change select field into an input text field, I use this script: it's an autocomplete library that create a list just below the input field. It calls a php file searching what I'm looking for, so you don't load all DB..
https://github.com/jhonis/bootcomplete
JS
$('#inputText').bootcomplete({
url: 'search.php',
method: 'post',
minLength: 2
});
PHP
$txt = $_POST['query'];
$helper = new PDO(CONNECTION_DNS, CONNECTION_USER, CONNECTION_PWD);
$helper->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// YOU MUST HAVE id AND label AS RETURN DATA
$stmt = $helper->prepare('SELECT P.Id as id, P.Code as label FROM TABLE_NAME WHERE Code LIKE :Query');
$stmt->bindValue(':Query', '%'.$txt.'%', PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
print json_encode($results);

Related

Passing data from an echo dropdown list using javascript

I have this dropdown list that is written using echo
But the select is not as expected
This is my select tag
$output.=" <select name='selectnewauthor' id='selectnewauthor' class='form-control input-lg selectnewauthor'>
<option disabled selected value>Select Author</option> ";
// Getting data from database
$getresourcetype = "Book";
$selectqry = "SELECT author_fullname FROM tbl_author_add WHERE resource_type = ? ORDER BY author_fullname";
$stmt_author = $mysqlconnection->prepare($selectqry);
$stmt_author->bind_param("s",$getresourcetype);
$stmt_author->execute();
$stmt_author->store_result();
$stmt_author->bind_result($author_fullname);
// Writing options
while($stmt_author->fetch()) {
$author_fullname = $author_fullname;
$output .= "<option value='{$author_fullname}'>{$author_fullname}</option>";
}
$output.="</select>
It sounds as though your #selectnewauthor element is dynamically-generated. As such, you need to attach the listener to an element available on page load, and make use of event delegation.
Essentially, instead of $("#selectnewauthor").on('change', function() ...
You're looking for $("document").on("change", "#selectnewauthor", function() ....

How to fill one combo box based an other selected combo box value by ajax

i want to fill a combobox options based on another selected combobox option
keep in mind that i have php code in the same page
<select name="idcataloguectg" class="form-control" id="idcataloguectg">
<!-- PHP CODE ##################################### -->
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=mywsite_db;charset=utf8', 'root', '');// connection to the server and DB
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());// if error
}
$respond = $pdo->query('SELECT * FROM catalogue');// my request
while ($data = $respond->fetch())// fetch into the table
{
?>
<!-- PHP CODE ##################################### -->
<option value="<?php echo $data['0']; ?>"><?php echo $data['1']; ?></option>
<!-- PHP CODE ##################################### -->
<?php
}
$respond->closeCursor(); // end of request
?>
<!-- PHP CODE ##################################### -->
</select>
<label>Categorie</label><br>
<select name="idcategorief" class="form-control" id="idcategorief">
<!-- PHP CODE ##################################### -->
<?php
$idcataloguectg = $_GET['idcataloguectg'];
try
{
$pdo = new PDO('mysql:host=localhost;dbname=mywsite_db;charset=utf8', 'root', '');// connection to the server and DB
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());// if error
}
$respond = $pdo->query('SELECT * FROM categorie WHERE id_categorie='.$idcataloguectg.'');// my request
while ($data = $respond->fetch())// fetch into the table
{
?>
<!-- PHP CODE ##################################### -->
<option value="<?php echo $data['0']; ?>"><?php echo $data['2']; ?></option>
<!-- PHP CODE ##################################### -->
<?php
}
$respond->closeCursor(); // end of request
?>
<!-- PHP CODE ##################################### -->
</select>
i tried to search for examples but all i found that they use an external php file that fill the options but in my example i have all of them in the same page
so what can i do
can you gives me the ajax script
For the second select field to change accordingly, you need to reload the page when the user changes the value of the category select field. To do that, change the select tag to
<select name="idcataloguectg" class="form-control" id="idcataloguectg" onChange="window.location.href = '/?idcataloguectg=' + this.value">
This will change the url to the same site (you may need to replace the / with the name of your php file), but with the idcataloguectg GET parameter set correctly.
If you do that, you might also want to change the option line for the categories to
<option value="<?php echo $data['0']; ?>" <?php if ($_GET['idcataloguectg'] == $data['0']) { ?> selected <?php } ?>><?php echo $data['1']; ?></option>
So that when a category was selected through the GET parameter, the right option is selected, instead of the default (first) one.
But it isn't a good idea to reload the whole page, instead you should do it with ajax, but that requieres you to put the logic for the second select tag in another file, for example category.php. That file should contain the following (that portion of the code would obiously be removed from the main file):
<!-- PHP CODE ##################################### -->
<?php
$idcataloguectg = $_GET['idcataloguectg'];
try
{
$pdo = new PDO('mysql:host=localhost;dbname=mywsite_db;charset=utf8', 'root', '');// connection to the server and DB
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());// if error
}
$respond = $pdo->query('SELECT * FROM categorie WHERE id_categorie='.$idcataloguectg.'');// my request
while ($data = $respond->fetch())// fetch into the table
{
?>
<!-- PHP CODE ##################################### -->
<option value="<?php echo $data['0']; ?>"><?php echo $data['2']; ?></option>
<!-- PHP CODE ##################################### -->
<?php
}
$respond->closeCursor(); // end of request
?>
<!-- PHP CODE ##################################### -->
Then change the first select tag to
<select name="idcataloguectg" class="form-control" id="idcataloguectg" onChange="$.get('category.php?idcataloguectg=' + this.value, function(data){$('#idcategorief').html(data);});">
The script uses jQuery and sends a request to the new php file category.php, with the category id as a GET parameter. When the request returns successfully with the options, they are places inside the second select tag, replacing the previous contents.
This has the benefit of only sending the needed data every time, reducing the traffic and computing needed drastically.
EDIT:
I put the js in the onChange attribute of the select tag. This code gets executed every time the selected value changes. You can also put the code in a script tag or file inside a function and then execute the function in the atribute.
I use the $.get function from jQuery for the ajax calls, which is a shorthand for the $.ajax function with a simple syntax. Read up on them here and here.
The script I used is the following:
$.get(
'category.php?idcataloguectg=' + this.value,
function(data){
$('#idcategorief').html(data);
}
);
It starts an GET ajax request to the file "category.php" with the get parameter idcataloguectg set and defines a callback function on success, which takes the response data and replaces the innerhtml of the second select tag with it.
But it is better to write like this:
$.get(
'category.php',
{
idcataloguectg: $('#idcataloguectg').val()
},
function(data){
$('#idcategorief').html(data);
}
);
This does the same, but defines the parameters in an object, which is more readable and also works with POST requests. Also, I replaced the this with a jQuery selector based on the id, because the this can betricky at times, so this is safer.
If you would want to have three select tags, the first can stay the same and the second script (which is called by the onChange attribute of the second select tag) would need to look like this:
$.get(
'second.php',
{
valueSelectOne: $('#idOfFirstSelectTag').val(),
valueSelectTwo: $('#idOfSecondSelectTag').val()
},
function(data){
$('#idThirdSelectTag').html(data);
}
);
replace second.php with the name of your php file, which return the values for the third input field and the id's accordingly. If you don't understand something related to the $, you should read up on jQuery.
Hope this helps.

PHP How do I get my form inputs to have data that is auto generated based on selection from database

This is a bit hard for me to explain and I don't really have any examples to show as I don't know how to do it.
What I am trying to do is to have fields automatically filled up for me based on my selection which is taken from my database.
Let's say I'm trying to fill data up for a casualties form and I'm getting my selection for my fields from a people's database and that database contains all the information of everybody inside, information such as the contact number, next of kin, full name, their IC etc etc.
Is there a way to display data such contact number, next of kin, IC number based on let's say their name inside the form itself?
$query = "SELECT * FROM staff";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
.... in the form itself
<tr>
<td><label><b>Staff ID</b></label></td>
<td><select name="staffID"><option value="">Select staff ID</option>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['staff_id']; ?>">
<?php echo $row['staff_id']; ?>
</option>
<?php } ?>
</select></td>
</tr>
The idea is, after they selected an ID from the dropdown box, additional fields will appear, giving the user more details of the staff such as their full name, contact number etc etc.
I can echo out all their ID and I know how to generate out additional fields but I don't know how to auto fill up data on those fields based on the staff_ID they selected.
Sorry if this is confusing, english is not my main language and I'm pretty terrible with programming
English is not my natural language (i`m from brazil).
In this case you will need to use AJAX. The easier way to do that is using Jquery (www.jquery.com). I will put here the easier way, but if cant help, tell me again.
---Let`s go --------------
<option id="reportedBy" name="reportedBy">
<option value="staff" data-name="Full Name of Staff" data-no="(222)2222-2222">
</option>
So you will make a script using jquery. When this option change his value, you will get the selected option value and get the others data using the dataset.
<script>
$(document).ready(function(){
$("#reportedBy").change(function(){
name = $(this).find(":selected").data("name"); //data-name less data-
no = $(this).find(":selected").data("no"); //data-no less data-
//Assuming your textfilds use the id "name" and no
$("#name").val(name);
$("#no").val(no);
});
});
</script>

How to get the values of div using its id after retrieving the values from database using php

I am trying to get the values of div elements using Simple HTML Dom Parser. Its working fine for only hard coded values. Here is the hard coded stuff.
<table>
<tr><td class='none'><div class='drag' id='d1'>1</div></td></tr>
<tr><td class='none'><div class='drag' id='d2'>2</div></td></tr>
<tr><td class='none'><div class='drag' id='d3'>3</div></td></tr>
Apart from these constant values i need to get the other id values which are displayed based on the selection from the drop-down menu.
<form method="post" name="order" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select id='test' name='test'>
<option value="">Please Select</option>
<option value='test1'>Test1</option>
<option value='test2'>Test2</option>
</select>
</form>
After the selection they click the continue button which redirects them to the same page and here is my script that displays id's from database.
<?php
$i=4;
if ($_SERVER['REQUEST_METHOD']=="POST")
{
$query = mysql_query("select * from test_demo where test_requested='$_POST[test]'");
while($result=mysql_fetch_array($query))
{
echo "<tr><td class='none'><div class='drag' id='d$i'>". $result['oid'] ."</div></td></tr>";
$i++;
}
}
echo "</table>"
?>
Now i want to get the order id's 1,2,3 and remaining id's retrieved from the database. In order to get these values i am using a Values button on click goes to retrieve.php file.
In retrieve.php file i am using Simple html dom parser to get the values. Here is the code.
<?php
include_once('simple_html_dom.php');
//test.php contains my hard coded html and php code
$html = file_get_html('test.php');
$temp = '1';
//usig div name we are retrieving the values
foreach($html->find('div#d5') as $e)
$result[]= $e->innertext;
print_r($result);
?>
In the place of d5 if i could mention d1 or d2 or d3. I could able to get the values 1,2,3 respectively. But i am unable to get the order id values which are retrieved from the database. The div ids for these elements starts from d4 and so on. Where could be I am going wrong?
There are several issues.
First, PHP scripts aren't run if you access them as ordinary files. You need to change the URL to go through the server:
$html = file_get_html('http://localhost/path/to/test.php');
Second, you need to provide the value of the test parameter in the URL, so it should be:
$html = file_get_html('http://localhost/path/to/test.php?test=test1');
Third, in test.php you need to access the parameter using $_GET, not $_POST, when it's accessed this way:
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$test = mysql_real_escape_string($_GET['test']);
$query = mysql_query("select * from test_demo where test_requested='$test'");
...
}

Splitting a Select Input for on page Dynamic Form Creation as well as sending value to Form

I need to split a select input in two parts in order to use one part for dynamic form creation on the same page and the second part to be sent to the receiving form.
This is what I have now to dynamically create the div below based on the select input selection:
$a = 0;
while ($row = mysql_fetch_array($result)) {
$people_array[$a] = array(
"ID" => $row['ID'],
"event" => $row['name'],
"time_needed" => $row['time_needed'],
);
$a = $a + 1;
}
$count = count($people_array);
<form>
<?php for($p=0,$p<$count,p++){
$segment_id = $people_array[$p][ID]; ?>
<select name="name_segment" id="name_segment">
<option value="female" >
<?php echo $people_array[$p][name]; ?>
</option>
<option value="male" >
<?php echo $people_array[$p][name]; ?>
</option>
</select>
<?php } ?>
</form>
<div id="name_segment_female" class="name_segment_input" style="display:none;">
Allow at least 30 extra minutes for bathroom usage.
</div>
<div id="name_segment_male" class="name_segment_input" style="display:none;">
No extra bathroom time needed.
</div>
and the javascript
<script>
$("#name_segment").change(function() {
var name_segment = $(this).val();
$(".name_segment_input").hide();
$("#name_segment_" + name_segment).show("slow");
});
</script>
Searching here on stackoverflow, I have found this post that got me started with this: <option value="{type:'amount',segment_id:'<?php echo $segment_id; ?>'} >. I just need to know how I can split this object up with javascript before submitting the page. I need to have the hidden div display dynamically using the same value from the option input as a more specific value that will be sent to the receiving page for the form.
First I changed options values all to be the same length for simplicity.
for example I left "male" the same but changed female to "fmle"
Then I changed the javascript:
$("#name_segment").change(function() {
var name_segment = $(this).val();
var local_segment = name_segment.slice(0,4);
$(".name_segment_input").hide();
$("#name_segment_" + local_segment).show("slow");
});
to parse out just the four letter section and use similarly as the original design. Then I changed the options values to <option value="fmle_<?php echo $segment_id; ?>" >. The segment_id will be parsed out server side after the submission of the form.
If completely necessary we can do a little more work to only send the segment_id as the original question asked but this will achieve the desired objective.

Categories