Jquery chosen plugin doesn't Work in ajax response - javascript

I have two select box. and I want to apply chosen plugin in both select box.
When No-1 Select box change then No-2 select box generate from AJAX response.
Chosen Plugin in No-1 work perfectly. But When No-2 select box generate from ajax then chosen plugin doesn't work in No-2 select box.
main.php
<tr>
<td>Select Location</td>
<td>
<select id="issue_type" name="issue_type" class="chosen-select">
<option value="" disabled="disabled" selected="selected">Select Location</option>
<option value="17">RM Store</option>
<option value="17">PM Store</option>
<option value="17">FG Store</option>
</select>
</td>
</tr>
<tr id="tr_product" name="product">
<td>Select Product</td>
<td></td>
</tr>
JS code for ajax
$('#location').change(function(){
if(this.value){
$('#td_avail_qty').html('');
$.ajax({
type:"GET",
url:"mat_issue.php",
data:{action:"ajax",sub_action:"location",location:this.value}
}).done(function(data){
$('tr#tr_product').show().children().eq(1).html(data);
});
}
});
mat_issue.php
$product_str = '<select id="product" name="product" class="chosen-select">
<option value="" disabled="disabled" selected="selected">Select Product</option>';
$location = $req['location'];
$sql_product = "SELECT l.`loccode`, l.`stockid`, l.`quantity`,s.description FROM `locstock` l INNER JOIN stockmaster s ON l.stockid = s.stockid WHERE l.`loccode` = '$location' AND l.`quantity` > 0";
if($query_fg = DB_query($sql_product,$db)):
while($data_product = DB_fetch_assoc($query_fg)):
$product_str .= '<option title="Available Quantity '.$data_product['quantity'].'" value="'.$data_product['stockid'].'">'.$data_product['description'].'</option>';
endwhile;
endif;
$product_str .= '</select>';
echo $product_str;
No-2 Select box generate from ajax successfully. But chosen plugin doesn't work in this select box.
I use this code for chosen plugin
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
And I use .chosen-select class in my select box

pass your chosen jquery function in your ajax success function...
may be this can help you out..
$('#location').change(function(){
if(this.value){
$('#td_avail_qty').html('');
$.ajax({
type:"GET",
url:"mat_issue.php",
data:{action:"ajax",sub_action:"location",location:this.value}
}).done(function(data){
$('tr#tr_product').show().children().eq(1).html(data);
$("#product").chosen({max_selected_options: 5}); //your chosen code for select tag
});
}
});
let me know if you face any other problem....

You need to load chosen after you have finished loading data in the select tag, Look at my snippet below
<script>
$('#subject_id').on('change',function(e){
var subject_id = e.target.value;
$.get('/ajax_subject_finder/'+subject_id,function(data){
$('#subject_paper_id').empty();
$('#subject_paper_id').append("<option></option>");
$.each(data,function(index,subObject){
$('#subject_paper_id').append("<option value="+subObject.id+">"+subObject.number+"</option>");
});
$('#subject_paper_id').chosen();
});
});

Related

Unable to fill the other fields on the basis of option selected

I want to fill the other fields on the form from database on the basis of option selected, but unable to do using php and javascript.I have attached json data I received in question. I want to fill other form fields when i select option from the form field houseowner_select and i want to show div app_houseowner when i select option from the select box having id applicant_is.
$("#applicant_id").on("change", function() {
var selected = $(this).val();
makeAjaxRequest1(selected);
});
function makeAjaxRequest1(opts) {
$.ajax({
type: "POST",
data: {
opts: opts
},
url: "get_houseownerinfo_applicant.php",
success: function(res) {
console.log(res);
debugger;
$("#applicant_wardno").val(res.ho_wardno);
$("#applicant_citizenship_no").val(res.ho_citizenship_number);
$("#applicant_phone").val(res.ho_phone);
}
});
}
<select name="applicant_is" class="form-control" ng-model="applicant.applicant_is" ng-change="callback_change_applicant_is($event)">
<option value="">--select--</option>
<option value="app_houseowner">घरधनी</option>
<option value="landowner">जग्गाधनी</option>
<option value="waris">वारिश</option>
</select>
<div class="app_houseowner">
<select class="form-control" name="houseowner_select" id="applicant_id">
<option value="">--Select--</option>
<option value="<?php if (isset($row11['id'])){ echo $row11['id'];}?>">
<?php if (isset($row11['ho_name_en'])){ echo $row11['ho_name_en'];}?>
</option>
</select>
</div>
<input type="text" name="applicant_phone" class="form-control" id="applicant_phone">
<select name="applicant_wardno" class="form-control" id="applicant_wardno">
<option value="">--Select--</option>
<?php for ($x = 1; $x <= 19; $x++) {
echo "<option value=".$x.">".$x."</option>";
}?>
</select>
<input type="text" name="applicant_citizenship_no" class="form-control" id="applicant_citizenship_no">
First of all remove or comment $("#applicant_salutation").val(res.ho_salutation) and $("#applicant_district").val(res.ho_citizenship_district) line in from your javascript code bcoz both id is not available in your html.
Also add dataType: 'json' in you ajax request
As i have checked applicant_wardno is select box and you have to set selected for displaying value in the select box instead of setting val.
check this link for setting selected value
You can debbug with an alert: alert(res.ho_wardno); and see if the value is being returned from the ajax query;
$("#applicant_wardno").val(res.ho_wardno);
alert(res.ho_wardno);
$("#applicant_citizenship_no").val(res.ho_citizenship_number);
$("#applicant_phone").val(res.ho_phone);

How to link drop-down menu to table using ajax

I am trying to populate a html table based on the selection from drop-down menu. i.e. when I selected an option from drop-down menu, it shows a table having description of that selected item fetched from the database like it fetches a row of that value and shows it in a table.
Now for this, I have to use Ajax & Jquery but i don't know much about ajax.
Can you please help me this?
Here is my code:
$("#courses").change(function(){
var course = $(this).val();
$.ajax({
url:'your php page url',
type:'post',
data:'course='+course,
success:function(response){
// your drop down box is in response
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="courses" id="courses" class="dropdownclass" ><option selected="selected" value="" disabled selected hidden >-- Select an option --</option>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('db');
$sql = "SELECT courses FROM table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value=' " . $row['courses'] ."'>" . $row['courses'] ."</option>";
}
?>
</select>
I don't know what to add in ajax and where to put the table and link it with drop-down menu. Kindly help me with this.
Here is sample static code to implement your functionality. You can add your dynamic content using sql and php.
index.php
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="paragraph-div">
<select id="courses">
<option value="cource_1">Cource 1</option>
<option value="cource_2">Cource 2</option>
<option value="cource_3">Cource 3</option>
<option value="cource_4">Cource 4</option>
</select>
<table id="myTable" border="1">
</table>
</div>
</body>
</html>
<script type="text/javascript">
$("#courses").change(function(){
var course = $(this).val();
$.post('data.php', {course: course}, function(response){
// your drop down box is in response
$("#myTable").html(response);
});
});
</script>
data.php
<?php
$course = $_POST['course'];
// Fetch data from db related to $course
$html = '<tbody>
<tr>
<td>Course Name : </td>
<td>Course 1 </td>
</tr>
<tr>
<td>Course Description : </td>
<td>Lorem ipsum Lorem ipsum Lorem ipsum</td>
</tr>
</tbody>';
echo $html;
die();
?>
Hope now it's clear.

Dynamic dropdown list not loading in modal

I have a dependent dynamic drop listing that works fine but as soon as I include it inside a modal, it doesn't work.
This is my code within the modal:
<script src="plugins/jQuery/2.1.1.jquery.min.js"></script>
<script src="js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#BugMaster').on('change',function(){
var bugmasterID = $(this).val();
if(bugmasterID){
$.ajax({
type:'POST',
url:'ajax/bugs/populate.cat.php',
data:'id_bug_master='+bugmasterID,
success:function(html){
$('#BugMasterCat').html(html);
}
});
}else{
$('#BugMasterCat').html('<option value="">Select BugMaster first</option>');
}
});
});
</script>
This is the html part of the form with the list :
<select class="form-control" name="BugMaster" id="BugMaster">
<option value="0" selected="selected">Please select module</option>
<?
while($r_b_c = mysqli_fetch_array($q_b_c)){
?>
<option value="<? echo $r_b_c['id_bug_master']; ?>"><? echo $r_b_c['name']; ?>
</option>
<? } ?>
</select>
This is the dependent list
<select name="BugMasterCat" id="BugMasterCat">
<option value="">Select country first</option>
</select>
The 'populate.cat.php' file looks like this:
if(isset($_POST["id_bug_master"]) && !empty($_POST["id_bug_master"])){
$id_bug_master = clean_data($_POST['id_bug_master']);
$q_cat = mysqli_query($sqllink,"SELECT * FROM bugs_categories
WHERE valid='1' AND id_bug_master='$id_bug_master'");
while($r_cat = mysqli_fetch_array($q_cat)){
echo "<option value='$r_cat[id_cat]'>$r_cat[name]</option>";
}
}
Then again, all this works fine if I load it directly from a page, but as soon as I open it in a modal, it fails and no categories are shown. I'm thinking it has to do with $(document).ready(function() that is not loading.
By not working I mean that the second drop down list is not being loaded.
Any help will be appreciated. Thank you.
I think no event is attached to your drop down
change your code:
... $('#BugMaster').on('change',function(){ ....
with
$(document).on('click', '#BugMaster', function() {
You need to load your JAVASCRIPT code from model itself, not from the parent / Base page.
But if you want to use another option that either use delegate or use inline javascript function call.
$(document).delegate('#BugMaster', 'change', function(){
//Implement your code here
});
OR
<select class="form-control" name="BugMaster" id="BugMaster" onchange="CALLJAVASCRIPTFUNCTIONHERE();">

Changing the select value in php

I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output

How to pass parameter as POST data on selection of an Select Box value, which will reload the same page?

I had two chained Select Boxes "pr_cat" and "sl_num" . The second select box values depend on the value selected in the first select box.
<tr>
<td width="257">Select Product Category:</td>
<td width="197">
<select name="pr_cat" id="Validprcat" onChange="reload(this.form)"><option value="">< Select one ></option>
<?php while($prd=mysql_fetch_object($select_query1)) {
if ($prd->cat_id==$pcat) { ?>
<option selected value="<?php echo $prd->cat_id?>"><?php echo $prd->category_name?> </option>
<?php } else { ?>
<option value="<?php echo $prd->cat_id?>"><?php echo $prd->category_name?></option>
<?php }}?>
</select>
</td>
</tr>
<tr>
<td>Select Serial Number:</td>
<td>
<select name="sl_num" id="Validslnum" onChange="reload2(this.form)"><option value="">< Select one ></option>
<?php while($slnum=mysql_fetch_object($quer)) {
if ($slnum->serialno==$pcat2) { ?>
<option selected value="<?php echo $slnum->serialno?>"><?php echo $slnum->serialno?> </option>
<?php } else {
?>
<option value="<?php echo $slnum->serialno?>"><?php echo $slnum->serialno?></option>
<?php }} ?>
</select>
</td>
</tr>
<tr>
I used the form reload javascript to reload the page with the value selected in the Select Box. I used GET method.
<script language=JavaScript>
function reload(form)
{
var val=form.pr_cat.options[form.pr_cat.options.selectedIndex].value;
self.location='delivery.php?pcat=' + val ;
}
function reload2(form)
{
var val=form.pr_cat.options[form.pr_cat.options.selectedIndex].value;
var val2=form.sl_num.options[form.sl_num.options.selectedIndex].value;
self.location='delivery.php?pcat=' + val + '&pcat2=' + val2 ;
}
</script>
But I want to do it using POST method how to do this ?
If you don't want to use ajax, and do it via POST method, so instead of
onChange="reload(this.form)"
call
onChange="formSubmit();"
<script>
function formSubmit()
{
document.getElementById("frm1").submit(); //frm1 is form id
//OR you can use
//document.frm1.submit(); //frm1 is form name
}
</script>
Note :- if you have any submit button in this form, don't keep it's name as submit, else you will have issues in your code.
I think what you're asking is pretty much this: JavaScript post request like a form submit
However, why do you want to reload the page at all instead of doing an AJAX call?
I give you the most simple and fastest way to do what you wanted,
AJAX:
cover both select box with '' tag,
<div id='first_select'>
<select id='first' onchange='populate_second_select(this.value)'>
<option>Select</option>
</select>
</div>
<div id='second_select'>
<select>
<option>Select</option>
</select>
</div>
call populate_second_select() function upon change done in first select box.
No in ajax,
function populate_second_select(value)
{
$.ajax({
method:'POST',
url:'ajax.php',
data: {value:value},
success:function(result)
{
document.getElementById("second_select").innerHTML=result;
showLightBox();
}
});
}
This is how your javascript function should look like,
on your ajax.php file, process the DB based on chosen value and 'echo' the whole select tag (second tag). That's it.
Here are few links would help you to get this done.
Link_1Link_2

Categories

Resources