I have a drop down list (ddlAccount) which i can choose an item from it and do a db query in test.php to retrieve corresponding data, then output an input element with the returned data.
This is my javascript code:
function load1(){
$('#divAccountNum').load('test.php?accountInfo=' + document.getElementById('ddlAccount').value , '' ,function() {
alert('Load was performed.')});
}
load1 function called when i change the dropdown list items, and it takes the value of the selected option and sends it to test.php in a parameter called "accountInfo".
my html:
<select name="ddlAccount" id="ddlAccount" onchange="load1();">
<option value="1"> Account1</option>
<option value="2"> Account2</option>
<option value="3"> Account3</option>
</select>
<div id="divAccountNum" >
</div>
And test.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']); //mysql query
//print an input holding account number as its value
echo "<input type='text' name='txtAccountNum' id='txtAccountNum' value='".$account->accountnumber."'/>";
}
The problem is that nothing happened when i choose an option (nothing appear in div (divAccountNum))
Any suggestions? Thanks in advance.
Edit:
I used #thecodeparadox 's bit of code and it works and i found a solution for the problem that i mentioned in the comments below which is that when choosing one item from the dropdown list it shows the value in input element and loads the form again. The solution is in:
jQuery Ajax returns the whole page
So my jquery code now looks like:
$(document).ready(function(){
$('#ddlAccount').on('change', function() {
$.get('testJquery.php?accountInfo=' + $(this).val(), function(accountNum) {
//console.log(accountNum);
$('input#txtAccountNum').val(accountNum);
});
});
And testJquery.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']);
$accountNum = $account->accountnumber;
echo $accountNum;
}
And at last i added input element in divAccountNum which has id="txtAccountNum"
Though you don't give enough info about your problem, but you can try this:
function load1(){
$('#ddlAccount').on('change', function() {
$.get('test.php?accountInfo=' + $(this).val(), function(response) {
$('div#divAccountNum').html(response);
}, 'html');
});
}
NOTE:
$('#ddlAccount').on('change', fires when dropdown change
$.get('test.php?accountInfo=' + $(this).val().. send a get(ajax) request to test.php with value selected from drop down
parameter response with in $.get() second parameter callback function is the response from the server
'html' as third parameter of $.get() for data type you return, as you return a html so it is html.
for more info read:
change()
$.get()
To get selected option value from select input use:
$('#ddlAccount option:selected').val()
Related
I use a dropdown menu where the user can select specific subjects. If a subject is selected via dropdown, a textbox pops up via ajax and the user can enter stuff.
The problem is that if the form has been submitted and stuff in the form was missing or if the user simply refreshes the page, the ajax content (the text box) disappears and only shows up again, when another subject is selected.
This probably stems from my ajax script, which uses change and thus only puts the ajax-input into the div when the dropdown is changed again:
$(function() {
$('#subjectapp1').change(function()
{
var self = $(this);
$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
$('#subjectqualidiv1').html(data);
});
});
});
My dropdown menu:
<select name="subject1" id="subjectapp1">
<option value="">Please choose</option>
<?php foreach ($subjects as $subject){ ?>
<option <?php if ($_POST['subject1'] == $fach['subject_id']) {echo 'selected';} ?> value="<?php echo $subject['subject_id']; ?>"><?php echo $subject['subject']; ?></option>
The div it is loaded into:
<div id="subjectqualidiv1"></div>
The ajax content (subjectpartial1.php) simply contains a text box in which the user can enter his qualification.
Is there a possibility that the ajax content is automatically loaded into the div when the page refreshes without the need to change the subjects again?
EDIT (WORKS): Based on the comments I tried the following, which yields the desired result:
$(document).ready(function () {
// For loading the ajax content on refresh/form submit
var subject1 = $('#subjectapp1');
$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: subject1.val()
},
function(data)
{
$('#subjectqualidiv1').html(data);
});
$('#subjectapp1').change(function()
{
var self = $(this);
$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
$('#subjectqualidiv1').html(data);
});
});
});
Thank you!
You can add your function that calls your AJAX to the $(document).ready() function which executes on page load. Be careful to check for valid data before executing your function because there may be instances when the page loads and the selector will be empty. For missing information you may want to look into the required attribute in HTML, which will prevent form submission if no data exists for that element. That will prevent a refresh for insufficient data.
You can do this along with your current code:
$(document).ready(function () {
$("#subjectapp1").trigger('change');
}
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 am working on a form in which changing one "select" element modifies the values of another "select" element. The values of both the elements come from a MSSQL database. What is the best way to implement code that can accomplish this?
There are two ways that I can think to do it.
Store the table into a javascript variable and make the onchange event of the first element modify the second element.
Send a GET request to the page and reload it, using PHP to modify the second element.
I don't like the first method because storing the database from the PHP side to the javascript side seems kind of hacky and really cumbersome to do. I don't like the second way either, because reloading the page disrupts the user experience and makes him have to scroll down again.
You should use AJAX to pull in data and populate the second select element. In a nutshell, AJAX is simply a separate page request that happens behind the scenes. You can use it to load a simple HTML page or partial and display it in a DOM element, or you can use it to dynamically retrieve structured data.
The best way to do this would be using JSON (JavaScript Object Notation). In this case, you would use Javascript to make an AJAX call to a PHP page, and that PHP page would take an argument in the query string that represents the value of the first select element. With that, you would make a call to your MSSQL database to get all of the corresponding options for the second select, and then echo those out. In turn, the Javascript you use to make the AJAX request can parse the response and interpret it as a JavaScript object literal, allowing you to loop through the results and do what you want with them.
Here's an example (I'm using jQuery, since it makes AJAX really easy).
At the top of your form page:
$(document).ready(function() {
$('#select1').change(function() {
var select1val = $(this).val();
$.getJSON('/path/to/response.php', 'select1=' + select1val, function(response) {
$('#select2').empty();
if(response) {
for(var option in response) {
$('<option/>').val(option.value).html(option.label).appendTo($('#select2'));
}
}
});
});
});
And then your response.php page should look like this:
<?php
$select1 = $_GET['select1'];
// Do validation here, to make sure it's a legitimate value for select1. Never trust the
// user input directly.
// Replace this with whatever code you use to make DB queries.
$options = $mydb->query("SELECT value,label FROM select2_options WHERE select1_value=?", $select1);
echo json_encode($options);
Use Ajax if you don't want to reload the page. Read more about AJAX
$('#select1').change(function() {
var value = $(this).val();
var dataString = 'id='+ value;
if(value != '')
{
$.ajax({
type: "POST",
url: "fetchOptionsForSelect2.php",
data: dataString,
success: function(html) {
$('#select2').html(html);
}
});
}
else
{
//reset select2
$('#select2').html("<option value=''>Select value from select1 first</option>");
}
});
Here is a stand-alone example that does what you want. It might look complicated at first, but AJAX via jQuery is quite straight-forward.
This example uses two files:
1) TEST.PHP - contains the javascript/AJAX, and the HTML with the <select> controls
2) PROCESS.PHP - receives data from test.php (via AJAX), runs a MySQL lookup on that data, returns HTML back to TEST.PHP
TEST.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#workers").change(function(event) {
var w = $(this).val();
//alert('Value of w is: ' + w);
//return false;
$.ajax({
type: "POST",
url: "process.php",
data: 'worker=' + w,
success:function(data){
//alert(data);
$('#laDiv').html(data);
}
}); //END ajax
});
}); //END $(document).ready()
</script>
</head>
<body>
Worker:
<select id="workers">
<option>Roy</option>
<option>John</option>
<option>Dave</option>
</select>
<div id="laDiv"></div>
</body>
</html>
PROCESS.PHP
<?php
$w = $_POST['worker'];
$ret = '
Fruit Options:
<select id="fruitopts" name="Select2">
';
if ($w == 'Roy'){
$ret .= '
<option>Apples</option>
<option>Oranges</option>
<option>Pears</option>
';
}else if ($w == 'John') {
$ret .= '
<option>Peaches</option>
<option>Grapes</option>
<option>Melons</option>
';
}else if ($w == 'Dave') {
$ret .= '
<option>Nut</option>
<option>Jelly</option>
';
}
$ret .= '</select>';
echo $ret;
Here's what happens:
a. TEST.PHP - User selects choice from dropdown "workers"
b. change() event fires, gets value of ("w"), and sends that to process.php
c. PROCESS.PHP receives a variable key named w in its $_POST[] array, stores in $w
d. PROCESS.PHP does a MySQL lookup on the selected worker (value of $w)
e. PROCESS.PHP constructs some HTML in a var called $ret, then ECHOs it out
f. TEST.PHP receives the HTML string inside the $.ajax success function
g. TEST.PHP calls the received data data (-1 for originality)
h. TEST.PHP injects the received HTML into the DIV with id="laDiv"
Hope that helps.
Use http://www.appelsiini.net/projects/chained
<script src="jquery.chained.min.js"></script>
<select id="mark" name="mark">
<?php
foreach($select1_opt as $opt)
{
echo "<option value=$opt>$opt</option>";
}
?>
</select>
<select id="series" name="series">
<?php
foreach($select2_opt as $opt)
{
echo "<option value=$opt>$opt</option>";
}
?>
</select>
I have a for loop that forms a list of check boxes based on information received from a mySQL database. Below is the for loop that forms the check boxes (unnecessary code removed).
for ($i = 1; $i <= count($descriptionIDsArray); $i++) {
$statuses = mysql_fetch_assoc(mysql_query(sprintf("SELECT status, description FROM status_descriptions WHERE description_id='$i'")));
$status = $statuses["status"]; ?>
<input type="checkbox" value="<?php echo $status ?>" <?php if ($check == 1) {echo "checked='checked'";} ?> onchange="checkBox()" /><?php echo $description ?><br />
<?php } ?>
Checking or unchecking a box calls the following function:
<script type="text/javascript">
function checkBox() {
var status = $("input:checkbox").val();
document.getElementById("test").innerHTML = status;
}
</script>
The only value that I can get to appear in "test" is the value of the first check box. If I echo $status throughout the initial for loop all the values appear correctly so the problem seems to arise when the Javascript code is retrieving the corresponding value.
If you still want to keep the inline event handlers, change it to:
onclick="checkBox(this);"
And change the function to:
function checkBox(chk) {
var status = chk.value;
document.getElementById("test").innerHTML = status;
}
Note that onclick is better supported with checkboxes and radio buttons than is onchange. Also, the reason for this change I provided is because passing this to the checkBox function references the element that the click was applied to. That way, you know that inside of checkBox, the parameter chk will be the specific checkbox that just changed. Then just get the value with .value because it's a simple DOM node.
Anyways, I'd suggest using jQuery to bind the click event. Something like:
$(document).ready(function () {
$("input:checkbox").on("click", function () {
var status = this.value;
document.getElementById("test").innerHTML = status;
});
});
But you can obviously use $(this).val() instead of this.value, but why bother? If you use jQuery to bind the events, just make sure you take out the onchange/onclick inline event handler in the HTML.
You can look at why to use input:checkbox and not just :checkbox as the jQuery selector here: http://api.jquery.com/checkbox-selector/
When you do
$('input:checkbox').val();
it is returning the first input of type checkbox on your form, not necessarily the one that is clicked.
To return the one that was actually clicked, you need to do something like this:
$(document).ready(function() {
$('input:checkbox').bind('click', function() {
clickBox($(this));
});
});
function clickBox(field) {
$('#test').html(field.val());
}
if you use a jquery, why bother with inline events?
You could write that like:
$(':checkbox').change( function(){
$('#test').html( $(this).val() );
//`this` is the checkbox was changed
//for check if item is checked try:
$(this).is(':checked') // boolean
});
If you pass that code before your checkboxes are placed make sure you invoke that code when document is loaded;
$( function(){
//code from above here
});
jQuery is well documented with lots of samples.
I think you'll like it docs.jquery.com
Sorry in advance everyone for this question as I know the cascading select boxes has been done to death but I can't seem to find any good help. I've tried various things but it all seems to fail and I'm not understanding why.
Here's the jquery I have currently:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
var vid = $("select#cat option:selected").attr('value');
var request = $.ajax({
url: "show_type.php",
type: "POST",
data: {id : vid}
});
request.done(function(msg) {
$("#result").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
}
Don't mind the first section of the code with the select#type and select#cat as these are for what I was trying to get the code to populate at first, however the .change is my trigger for the .ajax request. The rest of the code I'm merely trying to dump a simple return message into an empty div#result upon a successful ajax request.
I ran a test, and the var vid populates correctly.
Here's the simple PHP file I'm trying to call with the ajax:
<?php
$requ;
if (isset($_POST['id'])) {
$requ = 'Worked';
} else {
$requ = "didn't work";
}
echo $requ;
?>
I thought perhaps the problem was the id wasn't being passed properly so I altered the PHP script to give me any valid output regardless of whether the $_POST was set or not.
I won't post the HTML as I'm just trying to dump this all into a div while I test it. When I run the script I get the 'Request Failed' error message with a message of "error".
Here is the other jquery & PHP I have also tried, using the .post instead of the .ajax:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
$("select#type").html("<option>wait...</option>");
var vid = $("select#cat option:selected").attr('value');
$.post("show_type.php", {id:vid}, function(data){
$("#result").empty().append(data);
}, "json");
});
}
And the PHP to accompany this particular jquery:
$requ = $_POST['id'];
$ret = 'You selected: ' . $requ;
echo json_encode($ret);
Again, it all failed. I also tried the above code without using the json encoding/parameters. All I want to do is a simple (so I would think) cascading select dropboxes. The second box to be dependent of the first boxes selection. I'm beginning to think that this all just may not be worth it and just sticking strictly to PHP with links to resubmit the page with a GET and populate a new section or div with the results of the first click. Any help or suggestions you might have would be greatly appreciated, I've spent 2 solid days trying to figure this all out. Thanks in advance
Alright, I got it fixed. Thanks to Mian_Khurram_ljaz for making me take a different look at the hierarchical structure of the file. I was assuming that since the js was calling the php file, by placing the php file in the same folder as the js, I could call the php by using the url: show_type.php but that was actually wrong. The structure is considered from the actual page invoking the js and php, and therefore the url should have been js/show_type.php since I had the show_type.php file in my js folder.
It's always the little mistakes that take you days to figure. For those in the future looking to find decent code for cascading select drop boxes, here is my functioning and fully expanded code (which also includes a tri-level cascade)
jQuery:
function project() {
$("select#model2").attr('disabled', 'disabled');
$("select#brand2").attr('disabled', 'disabled');
$("select#project").change(function(){
$("select#model2").attr('disabled', 'disabled'); // if changed after last element has been selected, will reset last boxes choice to default
$("select#model2").html('<option selected="selected">Choose...</option>');
$("select#brand2").html("<option>Please wait...</option>");
var pid = $("select#project option:selected").attr('value');
$.post("handler/project.php", {id:pid}, function(data){
$("select#brand2").removeAttr("disabled");
$("select#brand2").html(data);
});
});
$("select#brand2").change(function(){
$("select#model2").html("<option>Please wait...</option>");
var bid = $("select#brand2 option:selected").attr('value');
var pid = $("select#project option:selected").attr('value');
$.post("handler/projBrand.php", {proj: pid, bran: bid}, function(data){
$("select#model2").removeAttr("disabled");
$("select#model2").html(data);
});
});
}
Just call the function in the $(document).ready of your js.
Notice the comment, having this 'redundant' call to disable and force the last box to select the default is just in case the user makes a selection in all 3 boxes but goes back to the first box and changes the selection.
Here is the php handler file:
<?php
include_once('../includes/file.inc');
$request = $opt -> getModelvBrand();
echo $request;
?>
The other handler file for the jQuery is nearly exactly the same, only invoking a different method in the class file.
And lastly, the HTML:
<form action="" method="post">
<select id="project">
<option value="0">Choose...</option>
<?php echo $opt -> getProject();?> //populates first box on page load
</select>
<select id="brand2">
<option value="0">Choose...</option>
</select>
<select id="model2">
<option value="0">Choose...</option>
</select>
<br /><br />
<input class="like-button" type="submit" title="Submit" value="" />
</form>
Thanks again Mian for making me take a different look at my file(s).
Hope this code helps someone else in the near future.