I have a working dropdown which gets its value from MySQL database in PHP.
I want to have a searchable dropdown instead of scrolling the list by using Chosen plugin.
Now, my question is how should I change my regular dropdown into Chosen dropdown?
(I need to know the procedure)
here is my code:
<form>
<select name="mySubmit" onChange="drawChart(this.value);">
<option value="">Select an option:</option>
<?php
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT `Name`, `id`
FROM info AS t1
where
(SELECT COUNT(*)
from info AS t2
where t2.Name = t1.Name AND (t2.`Date`) > (t1.`Date`)) = 0";
// Execute query
$result = mysql_query($sql_query) or die($sql_query."<br/><br/>".mysql_error());
while ($row = mysql_fetch_array($result)){
echo '<option value='. $row['id'] . '>'. $row['Name'] . '</option>';
}
mysql_close($con);
?>
</select>
</form>
Thank you in Advance.
first, you have to give a class or id to your select HTML element.
<select class="chosen" .... //same html/php code
Then in your javascript code, you call the jQuery chosen plugin to change this select to a chosen element like this:
$(document).ready(function(){
$('.chosen').chosen();
})
and it should work, you don't have to change anything in you php code, just give a class or id to you your select element so you can get if with jQuery selector. I advice you to read the chosen documentation
Related
I have run into a problem between two different coding languages, JavaScript and PHP. Now as you can see from the picture below in the webpage i have a select list and a add list .
In the select list I am querying the database to get the values out like in the code below shown:
<select name="opt_lable" id="select";>
<?php foreach ($distinctResult as $post) {?>
<option value="<?php echo $post['label'];?>"><?php echo $post['label'];?></option>
<?php };?>
</select>
Now for the input form that I have Add list, I add the value from the database and this value appears into the select option and also when I add the value I am creating a totally new file as shown below in the code:
<?php
include "conn.php";
if(isset($_POST['AddList'])){
$addLabelList=mysqli_real_escape_string($conn,$_POST['add_list_for_label']);
if(empty($addLabelList)){
header("LOCATION:../admin-panel.php");
}else{
$list=fopen("../".$addLabelList.".php","w");
$OpenExtPhp="<?php \n";
$CloseExtPhp="?>\n";
$Header="include 'header.php' ;\n";
$SidePanel="include 'side-Panel.php' ; \n";
$PostWindow="include 'post-Window.php';\n";
$CreatList="include 'create-list.php';\n";
$Footer="include 'footer.php';\n";
fwrite($list,$OpenExtPhp);
fwrite($list,$Header);
fwrite($list,$SidePanel);
fwrite($list,$PostWindow);
fwrite($list,$CreatList);
fwrite($list,$Footer);
fwrite($list,$CloseExtPhp);
$query="INSERT INTO posts(label) VALUES('$addLabelList')";
mysqli_query($conn,$query);
header("LOCATION:../admin-panel.php");
}
}elseif (isset($_POST['CancelList'])) {
header("LOCATION:../admin-panel.php");
};
the last thing that I do is link the values of the option list to that individual value that I created during submission of the value - as shown in the last code below which is a javascript file :
var sel=document.getElementById("select");
sel.onchange=function(value){
if(this.value=="home"){
var w=window.location.href="admin-Panel.php";
}else if(this.value=="Netherlands"){
window.location.href="Netherlands.php";
};
}
Am I able to link each value that I create with the form addList to the page which will be created during that procces of submission? Thnx to anyone who can help me out with this
If I understand your question, you want to send the value of the selected item to the php file that processes the POST data. If that is the case, you have two options
You can set a hidden form input (input type="hidden" value="") with the selected item and get the value in the file that processes the POST data
You can use $.ajax({}) to post the form data. That would allow you add the select data as POST data to your form
I have some php that connects to a database and creates a drop down list. I have a specific form in the HTML that I'd like to put the list in.
<body>
<form>
// some text inputs
// where i'd like the drop down to go
<?php makeList(parameter1, parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList(arg1, arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>
The only languages I'm allowed to use (apart from the sql) are php, html and javascript. As it is right now, makeList() returns an empty list. When I include opening and closing form tags in the function it returns a fully functional list, but then it acts as it's own form and I need to to be a part of the original form. Thanks.
EDIT: Sorry, forgot to mention the makeList function works fine when called within the php tags. It's when I call it in the HTML that it returns an empty list.
Firstly, you have some syntax issues with your script. It's not a valid HTML file, not a valid PHP file, and not a valid JS file.
If it were up to me, I'd define the PHP function at the stop of my script. Be careful to balance your opening and closing PHP tags. Something like this:
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
?>
And only after that would I start to output my HTML.
Now there are a couple of important things to note about that script I just posted:
the database code is not in here...I don't see any connection or query getting run or anything
In your script, this function doesn't look valid. arg1 and arg2 need a $ in front of each to be a valid PHP function. If it's a JS function you want then well, you are very confused and probably need to go back and figure out why this is not a valid JS function.
Your function refers to a variable, $result, that you have not bothered to define. It is not mentioned anywhere else in your script. It is most certainly not mentioned anywhere inside your function. For $result to be defined inside your function, you either need to pass it in as an array or declare it as a global:
global $result
Your function doesn't return anything at all. It just echoes stuff. This doesn't mean you can't use it, but it does mean that the function has no return value. Echoing the result of makeList won't output anything at all
So after that script above, you might have something like this:
<body>
<form>
// some text inputs
<?php makeList($parameter1, $parameter2); ?>
// submit button
</form>
Depending on what your parameters ($parameter1 and $parameter2) are this should work.
<body>
<form>
// some text inputs
<?php echo makeList($parameter1, $parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option>";
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>
I have an SVG map. When someone clicks on a state say, "Kansas" it displays a form and populates the state select box with the state that was clicked on say, it's Kansas. Code - This is working fine. This code is in the head.
var itemval= '<option value="'+data.name+'">'+ stateData[data.name].fullName+'</option>';
$("#SelItem").html(itemval);
When the form is submitted and it posts back to the same page, I'm using
<form method="POST" action="theform.php" onsubmit="return validateForm(this);">
When the page post back to the same page the select box is empty. The select box is there but with no option.
I've searched on Google I found the code below plus a few similar ways but they don't work. I've used this code in the head and under the select but no luck.
var selectedVal = $("#SelItem").val();
$("#SelItem").val(selectedVal);
**HTML**
<select id="SelItem"><option></option></select>
I've been working on this for hours but can't seem to find a solution.
Can someone tell me how to keep the select value after the form has been submitted and returns to the same page?
When the page loads you need to check for the presence of your posted value, and if it's there pass the php value to either the javascript code to populate the select option, or use it directly in the html creating the select options.
First off, you should give your select a name attribute in the html so the value is passed into the $_POST array in php:
<select id="SelItem" name="SelItem">
Here's one way you can populate it in javascript (note this code relies on the var stateData being in the same scope):
$(document).ready(function(){
<?php if (!empty($_POST['SelItem'])): ?>
var posted_state = '<?php echo $_POST['SelItem'];?>';
if (stateData[posted_state] !== undefined) {
var itemval= '<option value="'+posted_state+'" selected>'+ stateData[posted_state].fullName+'</option>';
$("#SelItem").html(itemval);
}
<?php endif; ?>
});
EDIT: An alternative to the above would be to put it in the html for the select tag:
<select id="SelItem" name="SelItem">
<?php if (!empty($_POST['SelItem'])): ?>
<option value="<?php echo $_POST['SelItem'];?>" selected>
<?php echo $_POST['SelItem']; // this would be better if you can replace it with fullname ?>
</option>
<?php else: ?>
<option></option>
<?php endif; ?>
</select>
Note this method has a couple issues as it's written. First off, the option text in this example won't be the state full name but the abbreviation. Next, you shouldn't trust the contents of $_POST because a malicious user can easily change it to a value you didn't intend it to be. It would be better to validate the value of $_POST['SelItem'] in your php code that handles the post to make sure it is actually one of the correct values before using it. That is why in the previous example I did the check if (stateData[posted_state] !== undefined) before attempting to add the value to your select.
EDIT:
To provide the state fullname from php you need an array of states defined on the php side also (I only see it in your javascript code which is client side).
So in php if you have something like:
$states = array(
'AK' => 'Alaska',
'AL' => 'Alabama',
// etc...
);
Then you can use the posted state abbreviation to get the fullname:
if (array_key_exists($_POST['SelItem'], $states))
$fullname = $states[$_POST['SelItem']];
Hi I have been trying to figure out how to prefill my from with data from my database based on a selection from a drop down menu. Been on it for a couple weeks cant figure it out...much thanks to anyone's help.
I have a form that has a dropdown selection menu that loads invoice ids from my database. I'm trying to prefill my form based on the value of the invoiceid selected.
In my database, column "invoiceidcopy" data shows as a selection for each different record/row value under my drop down menu.
If you notice in my image of my database table below you will notice the first row/record's invoiceidcopy field is blank..consequently...in my drop down menu ...the first selection is blank.
Ultimately my code below works only when i select the blank selection from the drop down menu but not for the other 2 selections?
Anything wrong with my code and or anyone know of a different way to achieve this...Thank u.
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){
var invoiceidcopy = $('#dropdown-select').val();
e.preventDefault();
$.ajax({
url: "/tst/orders2.php",
data: {
'invoiceidcopy': invoiceidcopy
}
}).done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_GET['invoiceidcopy']))
{
$invoiceidcopy= $_GET['invoiceidcopy'];
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = '".$invoiceidcopy."'";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die();
}
}
?>
Like minion stated, what exactly is sent as invoiceidcopy? From what I see the selecting the last one should send "THIS IS A TEST 2759f633-d6cb-4b3e-b4dc-3a4d0b54367..." exactly. It would be better to come up with another shorter Key for this field like "ThisIsATest-2759f633" or "ThisIsATest-201502070057". Also keep in mind that you want to sanitize the input to keep out SQL injection. Even though it is a drop down list, someone can use the HTML to change the variable.
On my path of slowly learning PHP I've decided to work on a dynamic drop down box to create a little find-a-product application for the small company I work for. I took a day to read examples others have put out of their dynamic drop down boxes and decided the method posted on CSS-Tricks was clean and efficient enough.
The problem I'm having is that the Javascript I'm using doesn't seem to be parsing and returning what I want it to. The MySQL query its supposed to build works as expected when I query my database directly (through Heidi) as well as when I load the script directly (explained at the bottom), but using JQuery to pass options through the script doesn't seem to work.
This is the main page with dropdown I'm using to test/build the script
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$("#type").change(function() {
$("#range").load("dynoptions.php?type=" + $("#type").val());
}).trigger("change");
</script>
</head>
<body>
<select id="type">
<option selected value="base">Please Select</option>
<option value="FM800">FM800</option>
<option value="FS100">FS100</option>
</select>
<br>
<select id="range">
<option>Please choose from above</option>
</select>
</body>
When the state of my first dropdown changes the javascript should be sending information to my PHP and receiving html to inject into the second dropdown.
And this is the PHP:
<?php
//creates DB connection
$dbHost = 'localhost';
$dbUser = 'foxmeter';
$dbPass = 'foxmeter';
$dbDatabase = 'foxmeter';
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
$result = array;
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
$choice = mysql_real_escape_string($_GET['type']);
//forms the query
$query = "SELECT DISTINCT sio FROM meters WHERE series='$choice' ORDER BY sio";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<option>" . $row{'sio'} . "</option>";
}
?>
You can test it live at new.foxmeter.com/dynamic.php
Also, new.foxmeter.com/dynoptionswithselect.php?type=FM800 is a version of the PHP script with
<select> and </select>
added before and after the script to test that the script is working (which it is).
Thanks!
The change() listener is never being called, probably because you're trying to register it before the DOM is ready.
What you need to do (and what is generally good practise with javascript) is make sure that the DOM is ready before you execute any script that relies on it.
There are a couple of ways of doing this - one is putting the script at the bottom of the page, but a better (safer) option is to use jQuery's document ready event handler:
$(document).ready(function(){
//your code here
});
The shorthand for which is:
$(
function(){
//your code here
}
);
So in your case:
<script>
$(function(){
$("#type").change(function() {
$("#range").load("dynoptions.php?type=" + $("#type").val());
}).trigger("change");
});
</script>