I need to load the content of a PHP file using jquery based on what is selected by the user in one or more select fields.
I can use...
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice").val() );
});
...to create the variable 'choice' and when the 'first-choice' field is set by the user.
However, what if I want to use 2 variables based on two drop down selectors, to set the variable 'choice' (based on the selection of #first-choice) and choice2 (based on the selection of #second-choice).
So I would want to load a PHP file something like getter.php?choice=first-choice&choice2=second-choice
here's how i would handle this situation..
don't treat your selects as ids. use a single class for all select options, then bind .change() to all selects using a class-based selector. if you do this, you can iterate over X number of selects, use their ids as the query argument variable and their values as each query value. I created a quick demo for you on jsfiddle. I also posted the code for you below....
Here is my demo on jsfiddle
<div>
<select class="php-options" id='first-choice' name='first-choice'>
<option value='1-0'>choose</option>
<option value='1-1'>1-1</option>
<option value='1-2'>1-2</option>
<option value='1-3'>1-3</option>
<option value='1-4'>1-4</option>
<option value='1-5'>1-5</option>
</select>
</div>
<div>
<select class="php-options" id='second-choice' name='second-choice'>
<option value='2-0'>choose</option>
<option value='2-1'>2-1</option>
<option value='2-2'>2-2</option>
<option value='2-3'>2-3</option>
<option value='2-4'>2-4</option>
<option value='2-5'>2-5</option>
</select>
</div>
<div id="request-url"></div>
$(document).ready(function(){
//treat your select options with classes,
//bind change event on each select
$('.php-options').change(function(e){
var urlValues = [],
parameterArgs = "";
//loop selects to build parameters
$('.php-options').each(function(i,v){
var optValue = $(this).val(),
optId=$(this).attr('id'),
parameter = ""+optId+"="+optValue;
urlValues.push(parameter);
});
//build parameter string
parameterArgs =urlValues.join("&");
//output query
$('#request-url').text('getter.php?'+parameterArgs);
});
});
Related
I have a query to select data from table(database) to show in List-view (table), than I want make code search data in list-view(table) by select-box without button submit.
this is my code in select box
<select onchange="selectrun(this);">
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
And this is my scrip
function selectrun(sel){
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
//what I return in response is a query because I want it's execute at my main page,that why I want pass it to $querr_select in php code but I don know my solution is good or not because I never do with ajax
}
});
}
This is my code in main page
$query_select = "SELECT * FROM `table`";
$result=pg_query($query_select ) or die(pg_last_error());
while($row_info=pg_fetch_array($result)){
//code for display view
}
*Note: in tab.php,I just pass id from main page to page tab.php for write a query to select in condition in where; when I alert response I get SELECT * FROM table WHERE ID ='1' And I want pass it to $query_select, is my idea but not work yet :(
I think what you are asking is how to display the result of an Ajax query. Is that correct?
<select onchange="selectrun(this);">
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<!-- A new HTML div for displaying Ajax call response: -->
<div id="response-area"></div>
<script>
function selectrun(sel){
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//Jquery sends response to browser div by setting html.
$('#response-area').html(response);
}
});
}
</script>
tab.php:
A basic concept of how you might return HTML via Ajax. This isn't great programming in terms of mixing HTML and PHP, but it it probably does what you want.
Assuming that your database table contains fields called 'field1' and 'field2', you can iterate through the array using the field names as array keys. Note that pg_fetch_array has additional parameters to select an associative array rather than a numerically indexed one.
<?php
$query_select = "SELECT * FROM `table`";
$result=pg_query($query_select ) or die(pg_last_error());
echo "<table>";
while($row_info=pg_fetch_array($result, NULL, PGSQL_ASSOC)){
echo "<tr>
<td>
$row_info[field1]
</td>
<td>
$row_info[field2]
</td>
</tr>";
}
echo "</table>";
?>
The modified code above should show you the response returned from tab.php when you change the option selected.
i have two select boxes and a link.i select one value from the first select box and another from the second select box and click on the link.the values have to get stored in an array each time without the previous value getting replaced.how can i do this without using multiple select box?
<select name="sq" id="sq" >
<option value=""></option>
</select>
<select name="as" id="as" >
<option value=""></option>
</select>
sorry forgot to mention..its in codeigniter
You can use change event to store the selected values.
Html
<select name="sq" id="sq" >
<option value="1">1</option>
<option value="2">2</option>
</select>
Javascript
arrSelected = []
$("#sq").change(function(){
arrSelected.push($(this).val());
});
With the added info from the comments, here is my suggestion:
HTML:
<div class="selectLine">
<select name="sq[]" >
<option value=""></option>
</select>
<select name="as[]" >
<option value=""></option>
</select></div>
<a id="addOption">
JavaScript:
$('#addOption').click(function(){
$('.selectLine').last().after($('.selectLine').outerHtml());
$('.selectLine').last().prev().hide();
});
PHP receiving the post:
foreach($_POST['sq'] as $key=>$name){
//Make sure you stay consistent with the keys to make sure the 2 values were entered at the same time.
echo '<p>'.$name.' is a '.$_POST['as'][$key].'</p>';
}
Adding [] to the end of the name of inputs will place them in arrays. But you need more than one if you want more than one value...
You can remove $('.selectLine').last().prev().hide(); to keep the lines displayed to the user so he can change the values if you want.
This would send the data with AJAX without page refresh:
Use for the link Submit data
Then add the following jQuery script: (you need to include jQuery library first)
$('#submitlink').click(function(event) {
event.preventDefault(); // Stops default link behaviour on click
$.ajax({
url: "yourphp.php", // where to send
data: 'sq=' + $('#sq').val() + '&as=' + $('#as').val(), // select values
type: "POST",
success: function(data){
// If you want to confirm
alert('Added');
}
});
});
Then in your php script store the $_POST data in either a database or session...
Session example, storing:
<?php
session_start();
if (!isset($_SESSION['sq']) $_SESSION['sq'] = array();
$_SESSION['sq'][] = $_POST['sq'];
if (!isset($_SESSION['as']) $_SESSION['as'] = array();
$_SESSION['as'][] = $_POST['as'];
?>
To retrieve the results you could use:
<?php
session_start();
if (isset($_SESSION['sq']) print_r($_SESSION['sq']);
if (isset($_SESSION['as']) print_r($_SESSION['as']);
?>
But of course this could be elaborated.
If you wish to have persistence in your website, then I would recommend looking into PHP Cookies.
In your case, you want to store an array, persistently, so you have a few options.
Either implement a HTML Hidden Element or you can use Serialization to store the array inside a cookie.
<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Cow</option>
</select>
if($_POST['submit'])
{
$animal=$_POST['animal'];
}
I have a dropdown like this. What I want, I want to get selected value and text in button submit using PHP. I mean if it's selected 1st one. I want to get both 1 and Cat
Is there a reason you didn't just use this?
<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Cow">Cow</option>
</select>
if($_POST['submit'] && $_POST['submit'] != 0)
{
$animal=$_POST['animal'];
}
$animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
$selected_key = $_POST['animal'];
$selected_val = $animals[$_POST['animal']];
Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.
You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...
<option value="2|Dog">Dog</option>
Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.
The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.
you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown
$("#dropdownid").val(); for value
$("#dropdownid").text(); for selected value
catch these into two variables and take it as inputs to ajax call for a php file
$.ajax
({
url:"callingphpfile.php",//url of fetching php
method:"POST", //type
data:"val1="+value+"&val2="+selectedtext,
success:function(data) //return the data
{
}
and in php you can get it as
if (isset($_POST["val1"])) {
$val1= $_POST["val1"] ;
}
if (isset($_POST["val2"])) {
$selectedtext= $_POST["val1"];
}
Does anybody know why I cannot specify the default value this way when it is pulling values from MySQL? I am ultimately trying to have it repopulate the dropdown lists with the appropriate $_REQUEST fields, so that editing can be easier.
$(document).ready(function(){
$("#region").load('getRecords.php?start=regions');
}); //jQuery initializations
...............
<select
class = "region"
name = "region"
onchange = "value = this.value;
$('.country').load('getRecords.php?region='+value)
">
<option>.....Reading database.....</option>
</select>
<script>$('.region').val('Africa');</script>
...............
This is the kind of info that gets placed
<option value = "">Select One Region-------</option>
<option value="Africa">Africa</option>
<option value="Americas">Americas</option>
<option value="Asia">Asia</option>
<option value="Australasia">Australasia</option>
<option value="Europe">Europe</option>
<option value = "">------or a Sub-Region------</option>
<option value="Alps">Alps</option>
<option value="Amazon">Amazon</option>
//ETC>>>>
I can only get the jQuery .val method to work for very simple setups.
Not quite sure what you are aiming for but maybe something like this will give you a nudge in the right direction (taken from the top of my head), probably has syntax errors.
$("select.region option[selected]").removeAttr("selected");
$("select.region option[value='Africa']").attr("selected", "selected");
try this:
document.getElementById("region").selectedIndex=0;//put index of the element which you want as default
and give id="region" in select tag
You need to have a valid <option value="Africa"> first before you can make that value become the default. <select> tags do not have arbitrary value attributes.
I recommend like below:
$('#region option[value="' + response_var[0].columnname + '"]').prop('selected', true);
Say I have two drop downs which are populated when the my jsp loads
<select id="Group" name="group"> -- first drop down
<option value="0001">1</option>
<option value="0002">2</option>
</select>
<select id="subGroup" name="class"> -- second drop down
<option value="0001-000">A</option> -- sub group associated with option value 001
<option value="0001-010">B</option>
<option value="0001-020">C</option>
<option value="0001-030">D</option>
<option value="0001-040">E/option>
<option value="0002-000">F</option> -- sub group associated with option value 002
<option value="0002-010">G</option>
<option value="0002-020">H</option>
<option value="0002-040">I</option>
</select>
Now I need to filter the second drop down based on the selected value in first drop down. I can't use the PHP code which uses the DB callback methods. in my script I have something like this.
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
$('#subGroup option').filter(function( {return!$(this).val().indexOf(groupVal)!=-1);}).remove();
});
the script is working fine, it removes all the options other then the one selected. but my problem is that next time when i select other value in first drop down, second drop down goes empty. I even worked with hide/show but guess they wont work with <select> :(
is there any way by which I can repopulate the second drop down when I selected some other option in first drop down?
If you are removing elements, you aren't getting them back. Use hide() and show() as you yourself suggested:
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
$('#subGroup option').hide();
$('#subGroup option[value^='+groupVal+']').show();
});
In other words, every time the #Group selectbox is changed, hide all options in #subGroup and show only the ones whose value attribute starts with groupVal.
Store all the options for the second select box into a array when the page loads. Then populate the select box from that array on change.
You are removing the second "batch" of options so they don't exists any more the next time you want to use them.
In order to do that you need to store all available options somewhere and then repopulate from that data set. for example
var availableOptions = {
'groupOne': {/* options as {value: '', text: ''} */},
'groupTwo': {/* options as {value: '', text: ''} */}
};
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
var sub = $('#Subgroup');
$.each(availableOptions[groupVal], function(i, data){
sub.append('<option value="'+data+'">'+data.text+'</option>');
});
There's also a related select box plugin by Remy sharp that I've had success with if you want to try:
http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/