Get options for select in forms from database - php

I'm programming the server side using PHP and got stuck.
I want to create a set of input fields using select tags for a form.
The options for the select should be fetched from my database and the option selected in the first input will decide the options in the second input.
For example, the two fields are country and state. First, the user selects their country name which will decide the list of states that appear in the state input field. I want the list to change dynamically when user changes the country.

You can do it in PHP submitting a select each time.
For example:
<form action="selectState.php" method="post">
<select name="country">
<option value="countryName">countryName</option>
...
</select>
</form>
then you get the value of $_POST['country'] in selectState.php and print the select the way you want it:
<form action="" method="post">
<select name="state">
<?php
// select use $_POST['country'] to customize the select option's
?>
</select>
</form>
A more user friendly solution (that does not require a new page or refresh) is use AJAX.
So you can use this kind of form:
<form action="selectState.php" method="post">
<select name="country" onchange="ajaxFunction(this.value)">
<option value="countryName">countryName</option>
...
</select>
<select name="state" id="stateList">
<!-- here we'll put the states we want -->
</select>
</form>
With this everytime the user change the select value ajaxFunction() is called and pass to the function the current value selected.
Here is the ajaxFunction (NOTE: this example use jQuery but you can do it in vanilla javascript):
function ajaxFunction(val){
$.ajax({
type: 'post', // choose the method
url: 'page.php', // choose the 'action' page
data: {
country:val // send the data
},
success: function (response) {
// this tell the browser what to do with the response of 'page.php'
// in this case we are telling to put everything we get to the HTML element with stateList id
document.getElementById("stateList").innerHTML=response;
}
});
}
The last thing you need its 'page.php' that simply query the DB (NOTE: this is pseudo code):
<?php
// Query the DB for the states with country = $_POST['country']
while(results){
echo '<option value="results[$i]">results[$i]</option>';
}
?>

Are you using a php framework such as Laravel (recommended) or Codeigniter (not sure if this is still in development).
If so you can construct a 2d php array of countries each with an sub array of its states.
This can be put directly into the rendering page (view).
Using something like
var countries_list =<?php echo json_encode($countries_array); ?>;
will directly inject this into a javascript array which you can use to populate the state select when the country select changes.
Or use ajax but that will be slower and hit the server more.

Related

Finding and replacing PHP Variable value from user drop down box

Is it possible in PHP to find and replace a PHP variable with a user defined value from a drop down box on a different PHP page.
Example:
PHP Page 1
$test = '1234';
PHP Page 2
Drop Down Values: (Find and replace $test variable with Drop Down selection)
1
2
3
4
Im have not found much information about this.
The purpose is to pass hexadecimal colours based on user choice.
PHP Variables are server-side variables. You can not change server side variables from client side directly.
Common approaches are: (Although both do same in background)
Using GET to send your data
Using AJAX to dynamically send, fetch and change DOM (Maybe preferred in our case)
On selecting the item on the Drop Down menu, you need to call a method which sends a data to your PHP page and you can change variables.
Your PHP page should handle a GET request change the variable to $test
$test = $_GET["sent_variable"]
While on AJAX, you need to something like:
$.ajax({
url: "your-php-page.php",
type: "POST",
data: { sent_variable: selectedVar}
}).done(function() {
//Something here after doing
});
Read more about AJAX here.
Note: You have to trigger AJAX on selecting drop-down menu. Read about that here.
Assuming the dropdown box is part of a form, you can use the 'post' method.
e.g.
<!--HTML-->
<form method="post" action="myScript.PHP">
<select name="myOption">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" value="GO">
</form>
//myScript.php file
<?PHP
$test = $_POST['myOption'];
echo $test;
?>
I actually have a page on my own site that uses similar functionality for passing hex colours if you want to have a look at the HTML source code http://www.wxls.co.uk/formatmyvba.html

Fill Single Input Based On Prior Select - MYSQL PHP JS?

I want to grab my customers phone number from a MYSQL database and auto populate it into an input box based on users selection of customers in a prior dropdown box.
I've managed to do this in the past when filling in larger amounts of data but what I've previously used seems like a lot of code to auto fill a single input box.
I know how to fill the customer phone based on the data passed from the prior page (although I've deleted that bit here) but I want that data to change dynamically as users use the dropdown.
There's got to be an easy way to do this but I'm a complete newb at js (and only barely proficient at PHP & MYSQL). Can anyone give me a hand?
My PHP/HTML:
$result = mysql_query("SELECT cust_id, name, phone FROM customers ORDER BY name ASC");
$customers = mysql_fetch_array($result);
<label for="customer">Customer:</label>
<select name="customer">
<option value="0">Add New Customer</option>
<? foreach ($customers as $customer): ?>
<option value="<?=$customer['cust_id']?>" <?=($customer['cust_id'] == $parts['cust']) ? "selected" : ""?>><?=$customer['name']?></option>
<? endforeach; ?>
</select>
<label for="custphone">Customer Phone:</label>
<input type="text" name="custphone" value="">
Let me know if you need anything else from me and thanks in advance for helping me out on this.
For this answer, I will use the jQuery syntax, jQuery is a free javascript library, and you'll certainly use it in the future, read more.
To resume, we'll use an event triggered by your select element, when his value is changed, we'll process an AJAX request with some parameters to a PHP page (ajax.php) which returns the phone number of the customer previously choosen.
First you need to include in your HTML web page, the jQuery script, with the <script> tag.
<script src="path/to/jquery.js"></script>
In a second time, we'll create a new javascript script (assuming you add some id's to your HTML elements):
<script type="text/javascript">
$(document).ready(function(){ // When the document is ready
$("select#customers").on("change",function(){ // We attach the event onchange to the select element
var customer_id = this.value; // We retirve the customer's id
$.ajax({
url : "path/to/ajax.php", // path to you php file which returns the phone number
method : "post", // We want a POST request
data : "customer_id="+customer_id, // You'll retrieve this data in your $_POST variable in ajax.php : $_POST['customer_id']
success: function(response) { // The function to execute if the request is a -success-, response will be the customer phone number
$("input#custphone").value(response); // Fill the phone number input
}
});
});
});
</script>
Now, you've all the gear to continue, you should read about jQuery and AJAX.
You just have to create the "ajax.php", retrieve your customer id with the $_POST variable, process the SQL query to retrieve the phone number, then, return it with an echo.
Sounds like you want to look into AJAX. jQuery.ajax() makes it pretty easy.
Basically, you have a page on the server that queries the database and returns a JSON encoded string that the javascript can convert (using jQuery.parseJSON)back into an array and populate the list!
Use .change() to bind an event to the dropdown's change event. This will fire whenever the selection changes. Inside, you want to get the value (see demo on that page) and send an AJAX request to the server.
The PHP script on the server will query the database and return a JSON string. In the success function of the jQuery AJAX block you can populate the new list with the decoded information. See this page for a tutorial on how to add items to a select.

simple AJAX dropdown 2

Ok this code seems to be working now (ajax getting the current selection) . But i now have another problem. When i use php $_GET method (for later database search), the output isnt just dropdown chosen word, but also generates another dropdown menu. There is also WAMP error - undefinex index for GET.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#select").change(function(){
$.ajax({
url: "test.php?selected=" +$(this).val(),
success:function(data){
$("#results").html(data);
}
}
)
})
});
</script>
<select id="select">
<option> something </option>
<option> something2 </option>
<option> something3 </option>
</select>
<?php
echo $_GET['selected'];
?>
<div id="results"></div>
<option>
needs to have value
<option value="test">
The problem is arising because you're self-referencing in the ajax call without accounting for the postback. Also the initial page load will throw an undefined index error because the selected key does not exist in the $_GET collection.
At the top of your test.php file:
<?php
if(array_key_exists('selected', $_GET))
{
echo $_GET['selected'];
die();
}
?>
Then remove your echo later on in your example.
Note that this is only to make your example work and show why it failed. Not to give a well-formed example of an AJAX request.
What is echo $_GET['selected']; supposed to display?
Can you give us some PHP code, as well?
And if you have an undefinex index for GET, it means that the array $_GET contains no key named selected. Where do selected come from?
If it comes from the JavaScript you gave us, then it should be select instead. (Also, naming your select with the keyword select is not recommended.)

javascript and PHP variable passing

I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
If I understand correctly, then yes, using AJAX is really your only choice.
Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.
Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.
Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js

Dynamic select box to populate a textfield using AJAX or jQuery and PHP

Is there any tutorial or code that help to poulate a textfield from a chosen value from a select box usuig AJAX or jQuery and PHP? Like in the picture ...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
//Please visit http://www.nokiflores.com
$(document).ready(function () {
$("#country").change(
function () {
$("#capital").val($(this).val());
}
);
});
</script>
<select id="country" name="country">
<option value="Delhi" >India</option>
<option value="manila" >phil</option>
<option value="tokyo" >japan</option>
</select>
<input type="text" readonly="readonly" value="" id="capital" name="capital" />
try this one:
if you want to use php you will do it another way using ajax.
Please visit http://www.nokiflores.com
I guess once you fill Delhi, the script can decide India, not opposite.
However if you want to make a subset of cities available, for selected country: that makes sense.
To your question, for this you would need a mammoth list of all major countries and there cities.
My approach:
In javascript make a array of 'country'.
Make a csv list for each country (like in.csv, us.csv etc.)
Now using JS populate country option fields.
Once country is selected, fire Jquery to fetch corresponding 'country-code.csv' using ajax.
Then Simply make a selection list of fetched city-names.
Note: Some people would object on CSV, choose any file format you find appropriate.

Categories