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.)
Related
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.
I have posted this a few times looking for some help, I cant seem to work out why i dont get any data from my dynamic drop down but i do from the 2 static fields. I did get some answers but mainly saying that i need to sort out the security, which i hope to learn next before anything is live online, everything looks good in Firebug including the trace for the http request, i think its a problem with the query i am trying to run, i will post this again and see if anyone can help me out before i address the security flaws.
Thanks alot for helping me out.
first is html, the subcategory is the problem, all items are stored in a javascript array and works fine, just not the query
<select name="Category" id="Category"
onchange="javascript: dropdownlist(this.options[this.selectedIndex].value);">
<option value="">Select Category</option>
<select name="subcategory" id="subcategory">
<option value="">Select Sub-Category</option>
</select>
<script>
$(function() {
$('#subcategory').change(function() {
$('#subcategory').load('results.php', {value: $(this).val()});
});
});
</script>
$category=$_POST['Category'];
$subcategory=$_POST['Subcategory'];
$destination=$_POST['Destination'];
$result = mysql_query("SELECT * FROM travel WHERE Category='$category'
AND Subcategory='$subcategory' AND Destination='$destination'")
or die(mysql_error());
$row = mysql_fetch_assoc( $result ) ;
echo to table (not posted as is working ok)
Where to even start? Your field name is 'subcategory'. You pass 'value' to results.php and you're attempting to retrieve 'Subcategory' form the $_POST array. You need to line all these names up.
I'm not sure whether the PHP there is the code for results.php or for whatever script the form is posted to, or are they the same? Regardless, whatever results.php needs, you need to include in the data you pass to load. For example, since you currently use 'value', you'd retrieve that via $_POST['value'], not $_POST['Subcategory'].
You only pass to php data from "#subcategory" form, not from "#Category", and with another id than you use in php code. And and you don't have a code for "destination", so I don't know where it should be taken from. Also it's better to put your code in $(document).ready when using jquery. It should be like that:
$(document).ready(function() {
$('#subcategory').change(function() {
$('#subcategory').load('results.php', {Subcategory: $(this).val(), Category: $("#Category").val() });
});
});
I created a script which get from my database the states and price of shipping by number of products.
So...I have 2 dropdown, one for quantity and the second one for state.
This is my main php file: http://pastebin.com/U6dncsZ6
This is the second php file (for database connect) - findcity.php : http://pastebin.com/AuEXrnpD
As you see, in my second php file I have this line:
<option value=<?=$row['price']?>><?=$row['title']?></option>
I want to display the shipping price from the database ($row['price'] on the page.
I specify that using "Inspect element" in my browser I can see the prices added as value for the states, like:
<option value="48.11">State</option>
Please help :(
Le: As I stated in a comment, I finally found that like here it's working: jsfiddle.net/Dkn4n/1/
But for some reasons, it's not detected but it's not working in my page, maybe because the value is not set in html, I can't see the values in source, only in "Inspect element". The value is set as I specified above, with $row['price']
Your select statement looks like this on the page:
<select id="provincia">
<option value="10.00">CA</option>
<option value="20.00">NY</option>
</select>
So using javascript/jQuery you can do the following to get the value of the selected option.
$(document).ready(function(){
$("#provincia").change(function(){
alert(this.value);
//do stuff here to set the value where you want it.
});
});
Here's a demo: http://jsfiddle.net/Dkn4n/
Adding to "Chase"s Answer:
$(document).ready(function(){
$("#provincia").change(function(){
$("#selectedprice").html(this.value);
//<div id=selectedprice></div> should show your value
});
});
and expanding it:
at this line:
document.getElementById('provinciadiv').innerHTML=req.responseText;
do
$("#provincia").change(function(){
$("#selectedprice").html(this.value);
//<div id=selectedprice></div> should show your value
});
again!
Because the "change" binding is gone once you replace the part...
I have a normal form with the combined selects for country and city, when I send the form no problem, but when I come back to the form for correct the mistakes I can't see the city I selected and the page didn't let me see the rest of the select. The script is:
$(document).ready(function(){
$("#country").change(function(event){
var id = $("#country").find(':selected').val();
$("#city").load('1select.php?id='+id);
$("#city").html(options);
$('#city option:first').attr('selected', 'selected');
});
});
I try with the ctrl+shift+k (I don't remember the name) in Firefox and the only error is "jquery is not defined". I don't know what's wrong with the code.
"to make sure you have the history of your selected values when you return to your form, you can use php as below (I may make some syntax errors as I am not PHP dev)
<select name="city">
<option value="birmingham" <?php if (isset($_POST['city']) && $_POST['city'] =='birmingham'){ ?>> selected <?php } ?>Birmingham </option>
</select>
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