How to populate dependable drop-down using Ajax and php [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi i want to manage data on drop-down menu using Ajax.
Databse Fields:
1.id
2.name
3.department
myDesgin.php
<select id="id"></select>
<select id="name"></select>
<select id="department"></select>
1.If i selected one drop-down menu want to change another drop-downs depend on selected value using Ajax.
2.Is there any code available, if i select one drop-down it go to another child window and display data as in table format(like report) using Ajax.
Thanks in Advance.
Please give me example code, because i am beginner to ajax , most welcome if someone provide explanation with code(for ajax).

Yes, check following jquery ajax code.
In this example, if you change "Department" then it will populate the listing of "Name" dropdown.
$(document).on("change", '#department', function(e) {
var department = $(this).val();
$.ajax({
type: "POST",
data: {department: department},
url: 'admin/users/get_name_list.php',
dataType: 'json',
success: function(json) {
var $el = $("#name");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
});

I guess you can do this:
make a global function which accepts two args, currElem, nextElem and dataObj:
function dynoDropdowns(currElem, nxtElem, dataObj){
$.ajax({
url:"path/to/file",
type:"post",
data:dataObj,
dataType:"json", // <-------------expecting json from php
success:function(data){
$(nxtElem).empty(); // empty the field first here.
$.each(data, function(i, obj){
$('<option />',
{
value:obj.value,
text:obj.text
}
).appendTo(nxtElem);
});
},
error:function(err){
console.log(err);
}
});
}
now your change events are:
$(function(){
$('select').on('change', function(e){
if(this.id === "id"){
var dataObj = {id:this.value};
dynoDropdowns(this, '#name', dataObj);
}else if(this.id === "name"){
var dataObj = {name:this.value};
dynoDropdowns(this, '#department', dataObj);
}
});
});

given select1 and select2 like this:
<select id="select1">
<option id="11" value="x">X</option>
<option id="12" value="y">Y</option>
</select>
<select id="select2">
<option id="21" value="1">1</option>
<option id="22" value="2">2</option>
</select>
then you can do something like this with jQuery:
$('#select1').on('change', function() {
$.ajax({
url: "test.html",
}).done(function(response) {
$('#select2').html(response);
});
This assumes your ajax call returns a string like
<option id="21" value="3">3</option><option id="22" value="4">4</option>
from your server sided file. If you return a json you have to decode it first, but this is the general gist of it. Take a look at the jQuery ajax() function

Although there are many codes available out there. I am writing most easy and basic code for you.
HTML
<select id="id" onchange="update_name(this.id)"></select>
AJAX Code
function update_name(id)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update_data.php?q="+id,true);
xmlhttp.send();
}
update_data.php (PHP code)
<?php
if(isset($_GET['q'])
{
$id= $_GET['q'];
//based on id run your query
}

Related

jquery calling variable after ajaxcomplete

The whole idea is to limiting the number checkboxes through dropdown, the approach is:
I have dropdown with following code
<select name="form[norequnit][]" id="norequnit" class="rsform-select-box">
<option value="">...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>01</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>02</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>03</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>04</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>05</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>06</label>
And some check boxes which are loading by ajax and below code is running to get dropdown value and also after ajax part to limit the number of selection based on the selected dropdown,
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#norequnit").on("change", function () {
$('#unitcount').html($(this).find('option:selected').text());
});
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
var nux = $('#unitcount').text();
$("input[name=chk]").change(function(){
var max= nux;
if( $("input[name=chk]:checked").length == max )
{
$("input[name=chk]").attr('disabled', 'disabled');
$("input[name=chk]:checked").removeAttr('disabled');
}
else{
$("input[name=chk]").removeAttr('disabled');
}
})
});
});
</script>
Problem:
variable "nux" get value only in first attempt by selecting dropdown, for example 5 so you to limit the boxes to 5 checks, but after this if you change dropdown to any other number the checkbox limitation remains on 5, in other word "nux" wont get new variable.
There's a few things wrong with your code, I'll try and go through them piece by piece with explanations and fixes.
Select onChange handling:
Separate your data from your view
Use val() instead of text() to get a select's current value
Code:
var nux; // 1. This will hold the value of nux for use in your script
$("#norequnit").on("change", function () {
nux = $(this).val(); // 1. Save the data, 2. Use using val()
$('#unitcount').html(nux); // 1. Use the data
});
Do you really need to use ajaxComplete?
I don't think ajaxComplete is the right way to go about responding to an ajax call (I could be wrong, I don't have all your code in front of me). Below I've done a best guess as to what you should (maybe, probably) do.
Code:
// Assuming you've got your ajax call somewhere else, use the "success"
// handler instead of the "ajaxComplete" function
$.ajax({
url: yourUrl,
method: 'get',
data: {
param1: 'value1',
param2: 'value2', // etc
},
success: function(html) {
// Presumably this is the HTML for your checkboxes, so add them
// to the DOM
$('#norequnit').after(html);
// And the only thing that really should go here otherwise is
// your bit of debug logging
console.log("Triggered ajax success handler.");
}
});
Use console.log if you are just outputting debug text
Maybe you actually do want to print the message on the page, if so you can ignore this. At very least, be aware of this wonderful debug-enabling tool. You can hit F12 (developer console) in your browser to view the output.
console.log("Triggered ajaxComplete handler.");
Move your checkbox onChange handler outside of any ajax closures
You could run into some incredibly hard to debug issues otherwise.
Code:
$(document).on('change', 'input[name="chk"]', function() {
// Handler code here
});
Notice the slightly different call to on, which uses the document object and includes the context parameter. This ensures any objects added to the DOM after the event handler is registered will still be handled.
All of it together
jQuery(document).ready(function($) {
var nux;
$("#norequnit").on("change", function () {
nux = $(this).val();
$('#unitcount').html(nux);
});
$.ajax({
url: yourUrl,
method: 'get',
data: {
param1: 'value1',
param2: 'value2', // etc
},
success: function(html) {
$('#norequnit').after(html);
console.log("Triggered ajax success handler.");
}
});
$(document).on("change", 'input[name="chk"]', function() {
if ($('input[name="chk"]:checked').length == nux) {
$('input[name="chk"]').attr('disabled', 'disabled');
$('input[name="chk"]:checked').removeAttr('disabled');
// Alternatively you could do this:
$('input[name="chk"]').not(':checked').attr('disabled', true);
} else {
$("input[name=chk]").removeAttr('disabled');
}
});
});

How to populate <select> options from another <select> tag in Laravel? [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi i want to manage data on drop-down menu using Ajax.
Databse Fields:
1.id
2.name
3.department
myDesgin.php
<select id="id"></select>
<select id="name"></select>
<select id="department"></select>
1.If i selected one drop-down menu want to change another drop-downs depend on selected value using Ajax.
2.Is there any code available, if i select one drop-down it go to another child window and display data as in table format(like report) using Ajax.
Thanks in Advance.
Please give me example code, because i am beginner to ajax , most welcome if someone provide explanation with code(for ajax).
Yes, check following jquery ajax code.
In this example, if you change "Department" then it will populate the listing of "Name" dropdown.
$(document).on("change", '#department', function(e) {
var department = $(this).val();
$.ajax({
type: "POST",
data: {department: department},
url: 'admin/users/get_name_list.php',
dataType: 'json',
success: function(json) {
var $el = $("#name");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
});
I guess you can do this:
make a global function which accepts two args, currElem, nextElem and dataObj:
function dynoDropdowns(currElem, nxtElem, dataObj){
$.ajax({
url:"path/to/file",
type:"post",
data:dataObj,
dataType:"json", // <-------------expecting json from php
success:function(data){
$(nxtElem).empty(); // empty the field first here.
$.each(data, function(i, obj){
$('<option />',
{
value:obj.value,
text:obj.text
}
).appendTo(nxtElem);
});
},
error:function(err){
console.log(err);
}
});
}
now your change events are:
$(function(){
$('select').on('change', function(e){
if(this.id === "id"){
var dataObj = {id:this.value};
dynoDropdowns(this, '#name', dataObj);
}else if(this.id === "name"){
var dataObj = {name:this.value};
dynoDropdowns(this, '#department', dataObj);
}
});
});
given select1 and select2 like this:
<select id="select1">
<option id="11" value="x">X</option>
<option id="12" value="y">Y</option>
</select>
<select id="select2">
<option id="21" value="1">1</option>
<option id="22" value="2">2</option>
</select>
then you can do something like this with jQuery:
$('#select1').on('change', function() {
$.ajax({
url: "test.html",
}).done(function(response) {
$('#select2').html(response);
});
This assumes your ajax call returns a string like
<option id="21" value="3">3</option><option id="22" value="4">4</option>
from your server sided file. If you return a json you have to decode it first, but this is the general gist of it. Take a look at the jQuery ajax() function
Although there are many codes available out there. I am writing most easy and basic code for you.
HTML
<select id="id" onchange="update_name(this.id)"></select>
AJAX Code
function update_name(id)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update_data.php?q="+id,true);
xmlhttp.send();
}
update_data.php (PHP code)
<?php
if(isset($_GET['q'])
{
$id= $_GET['q'];
//based on id run your query
}

localize dynamic drop down from database using jquery

This is the language select box.
<select name="lang" id="lang" browser="Indicated by the browser">
<option value="en">English</option>
<option value="fr">French</option>
<option value="ch">Chinese</option>
<option value="sp">Spain</option>`enter code here`
</select>
This is script i have written.
<script type="text/javascript">
jQuery(document).ready(function() {
loadBundles('en');
jQuery('#lang').change(function() {
var selection = jQuery('#lang option:selected').val();
loadBundles(selection != 'browser' ? selection : null);
jQuery('#langBrowser').empty();
if(selection == 'browser') { jQuery('#langBrowser').text('('+jQuery.i18n.browserLang()+')');
}
});
});
function loadBundles(lang) {
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
language:lang,
callback: function() {
updateExamples();
}
});
}
function updateExamples() {
var ex1 = 'Firstname';
var ex2 = 'Lastname';
var ex3 = 'Youremail';
var ex4 = 'Reenteremail';
var ex5 = 'Newpassword';
var ex6 = 'Dateofbirth';
var ex7 = 'Signup';
var ex8 = 'Itsfreeandalwayswillbe';
var ex9 = 'Birthlabel';
var ex10 = 'Termslabel';
var ex11 = 'Summarylabel';
var ex12 = 'PersonalLabel';
var ex13 = 'Interestlabel';
var ex14 = 'Addlabel';
var ex15 = 'Editlabel';
var ex16 = 'Deletelabel';
var spreadsheet_label = 'Spreadsheetlabel';
var invite_google_label = 'Invitegooglelabel';
var invite_facebook_label = 'Invitefacebooklabel';
var upload_label = 'Uploadlabel';
var subBut='Submit';
var dialogTitle = 'DTitle';
jQuery("#first_name_label").text(eval(ex1));
jQuery("#first_name_label1").text(eval(ex1));
jQuery("#last_name_label").text(eval(ex2));
jQuery("#last_name_label1").text(eval(ex2));
jQuery("#email_label").text(eval(ex3));
jQuery("#email_label1").text(eval(ex3));
jQuery("#reenter_email_label").text(eval(ex4));
jQuery("#new_password_label").text(eval(ex5));
jQuery("#date_of_birth_label").text(eval(ex6));
jQuery("#date_of_birth_label1").text(eval(ex6));
jQuery("#sign_up").text(eval(ex7));
jQuery("#label1").text(eval(ex8));
jQuery("#button").val(eval(ex7));
jQuery("#birth_label").text(eval(ex9));
jQuery("#terms_label").text(eval(ex10));
jQuery("#summary_label").text(eval(ex11));
jQuery("#personal_label").text(eval(ex12));
jQuery("#interest_label").text(eval(ex13));
jQuery("#add_label").text(eval(ex14));
jQuery("#edit_label").text(eval(ex15));
jQuery("#delete_label").text(eval(ex16));
jQuery("#spreadsheet_label").text(eval(spreadsheet_label));
jQuery("#invite_google_label").text(eval(invite_google_label));
jQuery("#invite_facebook_label").text(eval(invite_facebook_label));
jQuery("#upload_label").val(eval(upload_label));
jQuery("#submit_button").val(eval(subBut));
jQuery("#ui-dialog-title-dialog").text(eval(dialogTitle));
}
</script>
Everything is working fine for the labels. But in the case of dynamic drop down i got problem. How to localize the dynamic drop down data when the user selected the language.
The data in the drop down is coming from the database.
I have a language select drop down box, after selecting one language from dropdown list am able to change the text filed names and all other text in the language that is selected.
At the same time i have another dropdown, in that data is generated dynamically form the database. After the user selecting the language from dropdown list i have to change the data in this drop down list also. please suggest me if u have any idea.
Thank you.
I suggest you to use ajax for this issue.
You can bind ajax to first drop down and then fill secound dropdown by data which you get from back-end.
You can do something like this :
<select name='lang'>
<option value='eng'>Eng</option>
<option value='french'>French</option>
</select>
<!-- below div is another div whose data changes as per the language selected -->
<div id="another_div"></div>​
JS:
$("select[name='lang']").live({
change: function(e){
var selected_lang = $("select[name='lang'] option:selected").html();
data = {}
data['selected_lang'] = selected_lang;
$.ajax({
url: "required url",
data: data,
success: function(res){
$("#another_div").text(res); // if result is a direct text sent from server
// or
$("#another_div").text(res.content); //if result is an object with the required content present in the key 'content'
},
error: function(err){
alert("error occured");
}
});
}
});​
I would use one of the many Cascading jQuery Dropdowns:
http://www.ryanmwright.com/2010/10/13/cascading-drop-down-in-jquery/

Trigger onchange html event on page load too

Ok I have a onchange event on a select field. It now works great. When the dropdown "networks" is changed it refreshes the second dropdown. I also want the ajax code at the top to trigger on page load as well as onchange so the second list gets populated. This is due to it being on an edit page. Here is the ajax call im using first
function get_cities(networks) {
$.ajax({
type: "POST",
url: "select.php", /* The country id will be sent to this file */
beforeSend: function () {
$("#folder").html("<option>Loading ...</option>");
},
//data: "idnetworks="+networks,
data: "idnetworks="+networks +"&doc="+ <?php echo $row_rs_doc['parentid']; ?>,
success: function(msg){
$("#folder").html(msg);
}
});
}
now the two dropdown boxes
<label for="networks"></label>
<select name="networks" id="networks" onChange='get_cities($(this).val())'>
<?php
do {
?>
<option value="<?php echo $row_rs_net['idnetworks']?>"<?php if (!(strcmp($row_rs_net['idnetworks'], $row_rs_doc['network']))) {echo "selected=\"selected\"";} ?>><?php echo $row_rs_net['netname']?></option>
<?php
} while ($row_rs_net = mysql_fetch_assoc($rs_net));
$rows = mysql_num_rows($rs_net);
if($rows > 0) {
mysql_data_seek($rs_net, 0);
$row_rs_net = mysql_fetch_assoc($rs_net);
};
?>
</select>
<select name="folder" id="folder">
</select>
You can use .trigger() to trigger a change event onto the select-box so the onchange code will be called like it would if the user just switched the option.
jQuery('#networks').trigger('change');
Just include this into the load event/function for the page.
jQuery(document).ready(function() {
jQuery('#networks').trigger('change');
});
I'm not 100% clear what you want but the standard way to do something with JQuery when the page is loaded, is to use
$(document).ready(handler)
This waits till the page is "ready" which is better.
So, in your document head you'd have something like this...
<script type="text/javascript">
$(document).ready( function(){
do_some_stuff();
});
</script>
Can't you just call get_cities($('#networks').val()) when the DOM is ready?
$(function() { // will be run by jQuery when DOM is ready
get_cities($('#networks').val());
});

Triggering JSON request from 'click' event in a selector box using Mootools

Im trying to trigger an asynchronous JSON request when I select an option from an HTML selector box using mootools.
I have the following form element:
<form method="post" id="sel">
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
</form>
I'm using the following javascriipt/mootools to send a JSON request carrying the form info
window.addEvent('domready', function()
{
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response)
{
$('response').set('html', response.params)
}
}).get($('sel'));
})
});
to the following php script
$result['params'] = $_GET;
echo json_encode($result);
However, I'm told in Chrome's developer tools 'cannot read property "params" of null'
I don't see why request should be 'null' here.
Any ideas would be greatly appreciated
Hey man the answer to your question is in the question itself.
Your triggering the event when you are clicking on the select when like you said "select an option"
Click on the select would be wrong, however so would click on an option with in the select what your looking for is the onChange event the code would be as follows:
HTML
// Notice no form tag needed unless you are serializing other items
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
JAVASCRIPT
window.addEvent('domready', function(){
$('_selecor_id').addEvent('change', function(){
new Request.JSON({ // This must return a valid json object
url: "my_php_script.php",
data: {
'value': this.get('value')
}
onSuccess: function(responseJSON, responseText){
$('response').set('html',responseJSON.params);
}
}).send();
})
});
PHP
$result['params'] = isset($_GET['value']) ? $_GET['value'] : 'Not Set';
echo json_encode($result);
The responseJson variable will now contain something like {"params":"value_b"}
Try this code:
window.addEvent('domready', function(){
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response){
$('response').set('html',(response || this.response || this.responseText || {params: ''}).params)
}
}).get($('sel'));
})
});

Categories