I have a dropdown which contains data retrieved from a table. There is another dropdown which has some dynamic options. It means when a user selects a one option from the first dropdown. Only the matching options will be loaded into second dropdown from the same table. Everything works as I expected and the ouput is printed in the console properly (developers' tool).
But ajax response is not inserted into the second dropdown.
I went through similar questions in this forum, but nothing could help me to make it work.
I did these changes too
Changed dataType in Ajax to html.
Used append instead of html.
Even though I did above changes second dropdown is still empty. Surprisingly correct input is printed in the console.
What is printed in the console
<option value='10046'>ABC</option><option value='10048'>Nuwan</option>
When I inspect the console carefully I could see something like this
"" create_loan_request:169
Line 169 is console.log(html)
Below is my code and I am really grateful anyone to who could help me to find where the bug is.
First drop down
<div class="formBlock">
<label for="branch_id">Branch Name<span class="required">*</span></label>
<select id="branch_id" name="branch_id" class="textInput">
<?php
$branches = $branch->find_by_sql("SELECT * FROM branch");//this is an arry
foreach ($branches as $branch) {
echo "<option value='$branch->id'>$branch->branch_name</option> ";
}
?>
</select>
</div>
Second dropdown (will change dynamically)
<div class="formBlock">
<label for="cust_id">Customer Name <span class="required">*</span></label>
<select id="cust_id" ></select>
</div>
Script
$(function(){
$("#branch_id").bind("change",function(){
$.ajax({
type:"GET",
url:"create_loan_request.php", //same file
data:"branch_id="+$("#branch_id").val(),
dataType:"text", //changed this to html also
success:function(html){
$("#cust_id").html(html); // I have tried append also
console.log(html);
//inserting options to second dropdown
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
PHP code
<?php
//php code to populate customer dropdown based on branch
if(isset($_GET["branch_id"])){
$id=(int)$_GET["branch_id"];
$customers= Customer::find_by_sql("SELECT id,firstname,lastname FROM customer WHERE branch_id=".$id);
foreach ($customers as $customer) {
echo "<option value='$customer->id'>".$customer->firstname."</option>";
}
}
?>
P:S The whole html file is displayed as shown below
Try putting your jquery code in
$(document).ready(function(){
});
I check your code, without its database codes and it worked for me. I put my code here.
Test.php :
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$("#branch_id").bind("change",function(){
$.ajax({
type:"GET",
url:"server.php",
data:"branch_id="+$("#branch_id").val(),
dataType:"text",
success:function(html){
$("#cust_id").html(html);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
<div class="formBlock">
<label for="branch_id">Branch Name<span class="required">*</span></label>
<select id="branch_id" name="branch_id" class="textInput">
<option value='1'>a1</option>
<option value='2'>a2</option>
<option value='3'>a3</option>
</select>
</div>
<div class="formBlock">
<label for="cust_id">Customer Name <span class="required">*</span></label>
<select id="cust_id" ></select>
</div>
</body>
and server.php that works as the file for ajax call :
<?php
if(isset($_GET["branch_id"])){
echo "<option value='4'>a7</option>";
}
?>
You can check your db-related codes too.
Hope it can help :)
Related
Bellow shown code does these things
when i select Scholership Programs from select list the div element with class="mystaff_hide mystaff_opt1" will be shown
and then i select Family Income now div with class="mystaff_hide mystaff_opt2" will be shown. Now both are there on my window.
Up to this the code works fine
What i want is after submission of my form i want both of them are must be there on my window
<div class="row">
<div class="col-md-6 col-sm-6 pull-left">
<div class="form-group">
<legend>Options to Search</legend>
<select class="form-control firstdropdown" name="sel_options" id="mystuff">
<option>Select Options</option>
<option value="opt1">Scholership Programs</option>
<option value="opt2">Family Income</option>
</select>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt1">
<div class="form-group">
<label for="LS_name">Scholarship</label>
<select class="form-control" name="LS_name[]" id="LS_name" multiple="multiple">
<option value="opt1">Scholership1</option>
<option value="opt2">Scholership2</option>
</select>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt2">
<div class="form-group">
<label for="Family Income">Family Income</label>
<select multiple class="form-control" name="FamilyIncome[]" id="FamilyIncome">
<option value="opt1">Family Income1</option>
<option value="opt2">Family Income2</option>
</select>
</div>
</div>
This is my script
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/multi-select/0.9.12/js/jquery.multi-select.min.js"></script>
<script>
$( document ).ready(function() {
$('.mystaff_hide').addClass('collapse');
$('#mystuff').change(function(){
var selector = '.mystaff_' + $(this).val();
$(selector).collapse('show');
});
});
</script>
After lot of search i got this code which is shows only recent related selected option's div
<?php if(isset($_POST['sel_options']) &&
!empty(isset($_POST['sel_options']))){
?>
<script>
var selected_option = "<?php echo $_POST['sel_options']; ?>";
var selector = '.mystaff_' + selected_option;
//show only element connected to selected option
$(selector).collapse('show');
</script>
<?php } ?>
Take a look at localStorage or sessionstorage to store information about the state of webpage and read them after reload to restore the UI state
Example:
Localstorage
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Sessionstorage
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Or you may want to use AJAX
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
As you are using jquery, you may want to look at using Ajax in jquery.
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
hello i want to display data of business3's data according to business2's and business2's data according to business1's dropdown list but on change() of business1 i got data in response but I didn't get second on change() in dropdown list.
<!-- ajax code for first business starts here -->
<script>
$(document).on('change', 'select.Business1', function(){
var business1 = $('select.Business1 option:selected').val();
alert(business1);
var value = $(this).val();
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url('client_area/select_business_sub_cat'); ?>',
success : function (data){
$('#business2').empty();
$('#business2').append(data);
}
});
});
</script>
<!-- ajax code for first business ends here -->
// This script is not working. i can't find second change event.
<!-- ajax code for second business starts here -->
<script>
$(document).on('change','#business2',function(){
alert('Change Happened');
});
</script>
<!-- ajax code for second business ends here -->
I have tried with live() method also so alert called on first dropdown selection and then the ajax request calls so second drop down fills (Alternate for second script) ,
<script>
$(document).live('change', '#business2', function() {
alert('Change Happened');
});
</script>
Model function
public function select_business_sub_cat()
{
$business1 = $this->input->post('business1');
$result_sub_cat1 = $this->db->query("select category.id,subcategory.* From category LEFT JOIN subcategory ON category.id = subcategory.category_id where category.id = '$business1'");
$row_cat1 = $result_sub_cat1->result();
$data = array(
'id' => $row_cat1['0']->id,
'name' => $row_cat1['0']->name
);
echo "<option value='" . $row_cat1['0']->id . "'>" . $row_cat1['0']->name . "</option>";
// return $this->output->set_output($data);
}
View --
<div class="form-group">
<label>Business 1</label>
<select name="txtBusiness1" id="" style="height: 30px;width: 100%;" class="Business1">
<option value=""> Select Business </option>
<?php
$result_cat1 = $this->db->query("select * from category");
$row_cat1 = $result_cat1->result();
?>
<?php foreach($row_cat1 as $item){ ?>
<option value="<?php echo $item->id; ?>"><?php echo $item->name; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label>Business 2</label>
<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">
<option value=""> Select Business2 </option>
</select>
</div>
<div class="form-group">
<label>Business 3</label>
<select name="txtBusiness4" id="business3" style="height: 30px;width: 100%;" class="Business3">
<option value=""> Select Business3 </option>
<?php echo $abc; ?>
</select>
</div>
Maybe that's because by calling $('#business2').html(data); you remove the event handlers, from jQuery documentation: http://api.jquery.com/html
When .html() is used to set an element's content, any content that was
in that element is completely replaced by the new content.
Additionally, jQuery removes other constructs such as data and event
handlers from child elements before replacing those elements with the
new content.
One option would be to use empty and append like this
$('#business2').empty();
$('#business2').append(data);
instead of $('#business2').html(data);
The Script which is not working for you !!!
<script>
$(document.body).on('change','#business2',function(){
alert('Change Happened');
});
</script>
Try this in place of the above script :
$(document).on("change", "#business2", function(){
alert('Change Happened');
});
I have this coding that allows me show the .txt file contents of whatever file is selected from the drop down.
<form name="add" method="post" id="add" action="show.php">
Choose a file:
<select name="files" id="files" onchange="this.form.submit()">
<option value="File1">File1</option>
<option value="File2">File2</option>
</select>
</form>
with corresponding show.php (yes the purpose was to display only the last three lines of the file):
<?php
$ChosenFile = $_POST['files'];
$file = $ChosenFile.'.txt';
$contents = escapeshellarg($file);
$line = `tail -n 3 $contents`;
echo nl2br($line);
echo "<br><br>";
?>
Trying to get it to display the results below the select drop down instead of direct to the php itself with this code:
<script>
$('#files').on('change', function(){
$.get('show.php', function(data);
$('#result').html(data);
});
});
</script>
<div id="result"></div>
The php works and displays text contents but I can't get it to display below the drop down. What did I miss?
remove onchanged attribute form select tag
Choose a file:
<select name="files" id="files">
<option value="File1">File1</option>
<option value="File2">File2</option>
</select>
you must send form data to show.php file to get correct result back
<script>
$(function(){
$('#files').on('change', function(){
$.ajax({
url: 'show.php',
type: 'post',
data: $('form#add').serialize()
}).done(function(data) {
$('#result').html(data);
});
});
});
</script>
As your original html and php uses POST, you would need to use POST in your ajax script as well.
And you are not sending any data to your script.
So the result should be something like:
$('#files').on('change', function(){
$.post('show.php', $(this).closest('form').serialize(), function(data);
$('#result').html(data);
});
});
As mentioned in the comments, you also only need one event handler.
I am trying to display a HTML table in my index.php page with user registration data which process in table.php page. I am sending a value from a dropdown to the server for processing the data. These everything working for me. But my problem is when my index page load it is not display my table. If I need to display the table I want to select a value from the dropdown.
So anybody tell me how can I make a default value for dropdown (example 05) to display table when page is always loading.
This is my Jquery :
$('#filter-value').change(function(){
var filterValue = $(this).val();
//console.log(filterValue);
$.ajax({
type: 'post',
url: 'table.php',
dataType: 'html',
data: {filter: filterValue},
success:function(data){
$('#response').html(data);
//alert(data);
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
},
complete: function(){
//alert('update success');
}
});
});
This is HTML
<div id="manage_user">
<form action="" method="">
<div id="response"></div>
<button id="FormSubmit">Add New User</button>
</form>
</div>
<br />
<div style="margin: 0 20px 20px;">
<form method="post" action="">
<select id="filter-value" name="filter">
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
</div>
Thank you.
The easiest way to do this without rewriting your code would be to change the value of the drop down and then trigger the change event so that the your existing event handler gets called when the DOM is ready. Something like:
$(document).ready(function() {
$('#filter-value').val(5).change();
});
im trying to make a simple form which have a select menu with clone and remove button and once any of those select menus changed it must post the form using .Ajax call .
its working but have some issues
HTML
<form action="action.php" method="post" id="LangForm" >
<div id="fileds">
<select name="lang[]" id="lang" class="lang">
<option value="">Select</option>
<option value="arabic">Arabic</option>
<option value="english">english</option>
</select>
</div>
</form>
<button class="clone">Clone</button>
<button class="remove">Remove</button>
<div id="content"></div>
JS
$(function(){
var counter = 1;
$(".clone").click(function(){
$('#lang').clone().appendTo('#fileds');
counter++ ;
});
$(".remove").click(function(){
if (counter > 1) {
$('#lang:last').remove();
counter-- ;
}
});
$('.lang').change(function(){
$.ajax({type:'POST',
url: 'action.php',
data:$('#LangForm').serialize(),
success: function(response) {
$('#content').html(response);
}
});
});
});
it have 2 issues
first one when i click the remove button it remove the original select menu first then the cloned one and keep the last cloned one what i need is to remove the cloned menus first and keep the original one
second issue its submit form only when original menu changed what i need is to submit form whenever any menu changed original or cloned.
below is the PHP code from the action PHP page its something simple just to show result
PHP
<?php
print_r ($_POST['lang']);
?>
Thanks
HTML:
<form action="action.php" method="post" id="LangForm" >
<div id="fileds">
<select name="lang[]" class="lang">
<option value="">Select</option>
<option value="arabic">Arabic</option>
<option value="english">english</option>
</select>
</div>
</form>
<button class="clone">Clone</button>
<button class="remove">Remove</button>
<div id="content"></div>
Note: Id of the field has been removed.
JS:
$(function(){
$(".clone").click(function(){
// clone(true) will clone the element with event handlers intact.
$('.lang').last().clone(true).appendTo('#fileds');
});
$(".remove").click(function(){
var selects = $('.lang');
if (selects.length > 1) {
selects.last().remove()
}
});
$('.lang').change(function(e){
// console.log(e)
$.ajax({type:'POST',
url: 'action.php',
data:$('#LangForm').serialize(),
success: function(response) {
$('#content').html(response);
}
});
});
});
Demo:
http://jsfiddle.net/kFB5j/1/