There are some table in my DB. In "level" table, there are 3 level, "O level", "A level" and "Another level". And I have 3 subject table for these level. They are "sub_o", "sub_a" and "sub_another" and they have different subjects. I make a select option for "level" table by SQL query.
Code is given below:
<select name="" id="">
<?php
$result = mysql_query("SELECT * FROM vhlabel");
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['label_name']."</option>";
?>
</select>
And there are different subject for different level. I want when I will select "O level", then its subject will be displayed in check box. And when I select another level, another subjects will be displayed in check box.
What you want can easily be achieved with AJAX and by using jQuery the AJAX becomes more easier. So your solution with that can somehow be as below:
<select name="level" id="level">
<?php
$result = mysql_query("SELECT * FROM vhlabel");
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['label_name']."</option>";
?>
</select>
<div id="sub">
</div>
<script>
$('#level').on('change', function() {
var levelChangedTo = $(this).val();
//AJAX request to some server script that will pass the changed level
//And that script would return the HTML that would be appended
//to some other div which would have checkboxes.
$.ajax({
method: "POST",
url: "serverside.php",
data: { selectedLevel: levelChangedTo }
})
.done(function( response ) {
//Here append or replace the HTML according to your needs
jQuery('#sub').append(response);
});
});
</script>
Note: This is just a guideline through which you can achieve your goal.
Related
I have a page with a select list (gets successfully populated from mysql) and a text box. The text box has to be populated with a value from mysql based on the item selected in the list. But the ajax call to php is not working and i can not figure out what the issue is. I am just learning ajax and php, so a novice.. Please help. i am stuck with this for a long time.
<script>
$(document).ready(function() {
$('.selectpicker').on("change", function(){
var selected_data = $(this).find("option:selected").val();
alert(selected_data);
$.ajax ({
type: "POST",
data: { selected_data: selected_data },
url: "getoldcharity.php",
dataType: "json",
success: function(res) {
$('#charity_new').val(data.charity_new);
}
});
});
});
</script>
<form id="assign-fundraiser_form" class="form-horizontal" action="" method="post">
<div class="form-group">
<div class="col-md-3">
<select class="selectpicker form-control" id="fundraiser" name="fundraiser" required>
<option value="" selected disabled>Select a Fundraiser</option>
<?php
include('session.php');
$result1 = mysqli_query($db,"select concat(f_firstname,' ',f_lastname) fundraiser from fundraiser where f_company in (select contractor_name from contractor where company_name = '$_SESSION[login_user]') and f_status = 'Active' order by concat(f_firstname,' ',f_lastname)");
while ($rows = mysqli_fetch_array($result1))
{
echo "<option>" .$rows[fundraiser]. "</option>";
}
?>
</select>
</div>
</div>
<input type="text" name="charity" id="charity_new" />
</form>
<?php
include "session.php";
if (ISSET($_POST['.selectpicker'])) {
$ref = $_POST['.selectpicker'];
$query = $db->query("select f_charity charity_new from fundraiser limit 1");
$row = $query->fetch_assoc();
$charity_new = $row['charity_new'];
$json = array('charity_new' => $charity_new);
echo json_encode($json);
}
$db->close();
?>
There are a few problems that I've spotted from quick glance, so I've separated them below.
PHP
In your AJAX request, you are using data: { selected_data: selected_data } which means the PHP code will be expecting a POSTed key named selected_data but you're looking for .selectpicker. You seem to have mixed up a couple of things, so instead of:
$_POST['.selectpicker']
it should be:
$_POST['selected_data']
JavaScript
As Ravi pointed out in his answer, you also need to change your success function. The parameter passed through to this function is res not data, so instead of:
$('#charity_new').val(data.charity_new);
it should be:
$('#charity_new').val(res.charity_new);
MySQL
It also appears as though your query itself is invalid - you seem to be missing a comma in the column selection.
select f_charity charity_new from fundraiser limit 1
should be:
select f_charity, charity_new from fundraiser limit 1
or, seeing as you're not using the f_charity column in the results anyway:
select charity_new from fundraiser limit 1
You aren't using the value that is being POSTed either, meaning that whatever option is selected in the dropdown makes no difference to the query itself - it will always return the first record in the database.
Other
One other thing to be aware of is you're using a class selector on your change function. This means if you have multiple dropdowns with the same class name in your HTML, they will all be calling the same AJAX function and updating the textbox. I don't know if this is what you're aiming for, but from your code posted, you only have one dropdown in the form. If you only want that one dropdown to be calling the AJAX function, you should use an ID selector instead:
$('#fundraiser').on("change", function() {
// ...
}
I think, it should be
$('#charity_new').val(res.charity_new);
instead of
$('#charity_new').val(data.charity_new);
I have 2 selectboxes
<h3>Results</h3>
<select id="register_form" name="sport" />
<option value="Rugby">Rugby</option>
<option value="Cricket">Cricket</option>
<option value="Football">Football</option>
</select>
<?php
echo'<select name="match">';
echo'<option value="'.$row['event_id'].'">'.$row['team1'].' VS '.$row['team2'].'</option>';
echo'</select>';
?>
<input id="register_form" type="submit" value="Display" name="submit" />
User searches for a result by:
selecting sport type in 1st selectbox and then in 2nd selectbox option values are populated based on sport type.
Is it possible to do this in PHP without the user having to first press submit to get the $_POST value of sport type?
What is my best option here?
PHP always need to reload the page to refresh your informations, so, as anant kumar singh said, you need to use AJAX for that. And as yak613 said, jQuery will help you to use AJAX easily
1.Ajax is the only option what you asked for that(without page refresh)
When you use php it's only possible with page refresh. but with ajax without page refresh it's possible.
helping links are:-
Use jQuery to change a second select list based on the first select list option
https://www.daniweb.com/web-development/php/threads/372228/php-and-ajax-auto-populate-select-box
https://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax
You can use this Multiple Select Dropdawn lists: http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t , it can be used for multiple sets of Select lists.
I've faced with the same problem in my project. But the needed functionality was higher - not two dependent selectboxes and bigger number. I've written a simple function to load my selectboxes:
//formId - form where selectbox is
//name - attribute "name" of selectbox
//dataSourceUrl - url to PHP-file
//affectingField - string with value that filters the selecbox's data
function loadSelectbox( formId, name, dataSourceUrl, affectingField ){
//console.log('Loading data to selectbox name="'+name+'":');
var selectbox = $('#'+formId+' select[name="'+name+'"]');
if(selectbox){
//console.log("Selecbox found");
if(affectingField != null){
var affectingValue = $('#'+formId+' [name="'+affectingField+'"]').val();
dataSourceUrl += '?affectingValue='+affectingValue;
}
var options = selectbox.find('option');
var jqxhr = $.ajax({
url: dataSourceUrl,
dataType: 'text'
})
.done(function(data) {
//console.log(data);
if(data != ""){
var optionsObject = JSON.parse(data);
var i = 0;
console.log(optionsObject);
var options = [];
$(optionsObject).each(
function(){
options[i] = '<option value="'+$(this)[0]['val']+'">'+$(this)[0]['text']+'</option>';
i++;
}
);
selectbox.html(options);
if(urlParamsSet[name] == false){
setParamFromUrl(name);
}
}
else{
selectbox.html('<option value="">Все</option>');
}
})
.fail(function() {
alert("Problems with server answer");
})
selectbox.prop("disabled", false);
}
else{
console.log("No selectbox with such name");
}
}
Not saying that this code is perfect, but it works. PHP-file must return the values to selecbox in JSON format (convert from with structure: array(index, value, text) ).
I have created a script which fills the second combobox with the value of the first one. But it is not quite what I want to do. I want to fill the second combobox with the result of a SQL query based on the item which was selected in the first combobox.
Here is my javascript:
<script type="text/javascript">
function selectDropdown(){
var dropdownValue=document.getElementById("dropdown").value;
$('option[value=st]').text(dropdownValue);
}
</script>
first combobox:
<select id="dropdown" name="dropdown" onchange="selectDropdown()">
<option value="dd">--take an option--</option>
<?
$standard = Env::value('standard');
if (!$status)
$statement = "select code from standard";
foreach ($db->query($statement )->fetchall() as $row)
echo "<option".($row == $standard ? ' selected ' : '').">$row[0]</option>";
?>
</select>
and the second one in which I want to show the result of the query: $q= select request.code from request inner join standard on ( request.standard_id=standard.id) where standard.code=$st.
<select name='st' class='txt'>
<option value="st"><? echo $st; ?></option>
</select>
Can anyone give me a hint where I should put query execution? Or just point me what I am doing wrong?
Use jQuery's ajax call to make a request to the server each time when first dropdown selection has been changed. On the server side create a script which will receive that request and return corresponding records for 2nd dropdown in JSON format, which then can be easily processed by javascript. For using ajax see this link: http://api.jquery.com/jQuery.ajax/
It will be like:
jQuery.ajax({
method: "POST",
url: "http://domain.com/path/to/script.php",
data: value_of_selected_item_from_first_dropdown,
success: function(response) {
// Set 2nd dropdown values to those received via response
}
dataType: "json",
});
Is there any way I can select a certain value in a dropdown list and according to that selection display a second dropdown list?
I know how to do it with just normal words, but what if I use variable names?
University Name: <select name="university" id="university">
<?php
while($row = mysql_fetch_array($uniName)) {
echo "<option>" . $row['uni_name'] . "</option>";
}
?>
</select>
<br/>
Course Name: <select name='course' id='course'>
<?php
while($row = mysql_fetch_array($courseNames)) {
echo "<option>" . $row['course_name'] . "</option>";
}
?>
</select>
So as you can see, in the first dropdown list I've added all the retrieved university names from my database. I did the same for the courses as well.
Now how can I modify the code below:
$(document).ready(function() {
$('#course').hide();
$('#university').change(function () {
if ($('#university option:selected').text() == "Harvard University"){
$('#course').fadeIn('slow');
}
else {
$('#course').fadeOut('slow');
}
});
});
Instead of "Harvard University", I want to put a variable there according to what the user has selected. Something like $university_name and then I'll create a new query and display only the courses belong to a certain $university_name.
As already stated in my comments, I recommend using AJAX to fill the course box.
$.ajax("getCourses.php", {
data: { UID: uid },
type: 'POST',
done: function(result) {
$("#course").html(result);
});
This will fill the select tags with whatever getCourses has for output.
UID would of course be the ID of the university in question.
This page has all the info you need. For further information and examples, Google is your friend :)
So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});