How to update values of dropdown using another dropdown with AJAX nodejs? - javascript

I have two dropdowns. One is for selecting the Main category, the second for selecting the sub category.
I want to be able to populate the sub category based on the Main category selected.
What I have tried so far is using JQUERY and AJAX to listen to change in the value of the dropdown using jquery and send an ajax request to the relevant route.
View
<div class="form-control">
<label for="category">Category</label>
<select name="category" id="category">
<option value='Men'>Men</option>
<option value='Women'>Women</option>
<option value='Sports'>Sports</option>
</select>
</div>
<div class="form-control">
<label for="subcategory">Sub Category</label>
<select id="subcategory" name="subcategory">
</select>
</div>
AJAX and JQUERY
$("#category").on("change", function () {
$("#subcategory").empty();
showValue($(this).val());
});
var data = {};
function showValue(val) {
console.log(val);
data.category = val;
$.ajax({
url: "/admin/update-list",
type: "POST",
data: data,
success: function(result) {
updateDOM(result);
},
error: function (err) {
console.log(err);
}
});
};
var updateDOM = function (result) {
var data = result.data;
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
$("#subcategory").append("<option>"+ data[i] +"</option>");
};
};
/admin/update-list Route
router.post('/update-list', (req,res,next) => {
let data = [];
let category = req.body.category;
console.log('From the ajax call, category is' + category);
if(category = "Men") {
data = [
'Sneakers',
'Boots',
'High Heels',
'Litas',
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Women") {
data = [
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Sports") {
data = [
'Soccer Boots',
'Rugby Boots'
];
res.status(200).json({data});
res.end();
}
});
No matter what option I choose, the second dropdown returns the same data.

I would do this in PHP. Hopefully this conveys what you could adapt to your situation:
<select name="foo" >
</select>
ajax call
$.ajax({
type:'POST',
url:'your_code_page.php',
data:'param1='+variable,
success:function(html){
$('[name="foo"]').html(html);
}
});
PHP post back
echo "<option value=''>Please select a thing</option>"; <<outside loop
while ($row = sqlsrv_fetch_array($results)) {
$value = $row['value'];
$display = $row['display'];
//-display the result of the array
echo "<option value= " . $value . ">" . $display . "</option>"; << options returned in post
}

Related

select multiselect values from ajax resonse after edit button click

I have an Edit button. When onclick event is triggering data from the main table is showing in an input field, but related data from pivot does not get selected from JSON response. In JSON output, I can view both main table data with pivot data related to particular id. But this data is not get selected in a multi-select element.
Main Table : 1)SchoolSubject 2)StudentClass
Pivot Table: Student_Class_School_Subject
Controller
public function EditSubject(Request $request)
{
$id = $request->id; //get id from blade
$subject = SchoolSubject::with('class')->where('id',$id)->first(); //select subject data match with id with class stored in pivot
return response()->json($subject); //output comes with subject and class stored in pivot
}
edit.modal.blade.php
<div class="controls" id="classSelector">
<select name="class_id[]" multiple="multiple" id="classSelect" required="" class="form-control">
<option value="-1" selected="" disabled="">
Select Class
</option>
#foreach ($allClassData as $class)
<option value="{{ $class->id }}">
{{ $class->name }}
</option>
#endforeach
</select>
</div>
view.blade.php
#section
<script>
$(document).on('click', '.editIcon', function(e) {
e.preventDefault();
let id = $(this).attr('id');
var _url = '{{ route('subject.edit.route') }}';
$.ajax({
url: _url,
method: 'get',
data: {
id: id,
_token: '{{ csrf_token() }}'
},
success: function(response) {
console.log(response.class);
$("#subject_id").val(response.id);//data from main table got successfully from same json response
$("#subject_i").val(response.subject); //data from main table got successfully from same json response
var pivotData = response.class; //this is data from pivot table but how to select multislect select box value from this json response
jQuery("#classSelect option").each(function() {
if (jQuery.inArray($(this).val(), response.class) != -1) {
$(this).prop('selected', true);
};
}); //this query is not working
/*var newHTML = [];
for (var i = 0; i < response.class.length; i++) {
newHTML.push('<span>' + response.class[i] + '</span>');
console.log(response.class[i])
}
$("#resultchecker").html(newHTML.join(""));*/
}
});
});
</script>
#endsection
JSON response from pivot table using response.class
JSON response from pivot table using response
Because you have a nested array of objects in your JSON, you have to loop once more and select the id. I'm sure there are better ways to do this, but at least you get the idea.
Change this part
jQuery("#classSelect option").each(function() {
if (jQuery.inArray($(this).val(), response.class) != -1) {
$(this).prop('selected', true);
};
}); //this query is not working
Like this
jQuery("#classSelect option").each(function() {
var $this = jQuery(this);
response.class.forEach(element => {
if($this.val() == element.id) {
$this.prop('selected', true);
}
});
});

Controller not getting called though AJAX

I have a jsp page with 2 dropdown. the second dropdown should populate based on the value selected from first dropdown I am using AJAX for this to call a controller method on selecting the first dropdown to return the values for the second dropdown as json. On clicking submit entire form will be submitted to controller method. But on selecting the first dropdown, I am not getting any request on the controller method.
Jsp file
alert("Ok");
("#selectCategory").onChange(function() {
var categoryId = $(this).val();
alert(categoryId);
$.ajax({
type: 'GET',
url: "/categories/" + categoryId,
success: function(data) {
var slctSubcat = $('#selectSubcat'),
option = "";
slctSubcat.empty();
for (var i = 0; i < data.length; i++) {
option = option + "<option value='" + data[i].id + "'>" +
data[i].subcateogory_name + "</option>";
}
slctSubcat.append(option);
},
error: function() {
alert("error");
}
});
});
<form action="/show" method="post" modelAttribute="model">
<select class="form-control" id="selectCategory" name="sel">
<option value="Alto">Alto</option>
<option value="Esteem">Esteem</option>
</select> <br>
<select class="form-control" id="selectSubcat">
<option value="-1" label="-Select-" />
</select>
<input type="Submit" value="Submit" />
</form>
Controller method
#GetMapping("/categories/{categoryId}")
#ResponseBody
public List<String> get(#PathVariable("categoryId") String categoryId)
{
System.out.println("inside controller get "+categoryId);
ArrayList<String> l= new ArrayList<String>();
if(categoryId.equals("Alto"))
{
l.add("Alto Model 1");
l.add("Alto Model 2");
return l;
}
else if(categoryId.equals("Esteem"))
{
l.add("Esteem Model 1");
l.add("Esteem Model 2");
return l;
}
return null;
}
If I make a separate rest call to that controller method , I am getting the response as json [
"Esteem Model 1",
"Esteem Model 2"
], but through ajax, the request is not going.I am new to Ajax. Can someone please correct me if the below ajax code is wrong ?

Running SQL query after AJAX completes

I currently have 2 html dropdowns. Once I select from one, it filters the data in my HTML table and displays data based on the selection. I can also make changes to each row and, by clicking a save button, run an update query that updates the table. After, running that update, I want it to re-run the same query that was used to filter the results based on the dropdown selection so you can see the most up-to-date results of what you selected after clicking save and running the update statement. Right now, you can see that I have window.location.href = window.location.href; under the success callback in my AJAX function, but that reloads the entire page and runs the default query that displays on page load, so that doesn't work for me.
All of my queries that filter the table results after a dropdown selection are in my dropdown-display.php page that is called once I select something.
HTML Dropdowns:
<form name="testForm" action="">
<select id="collector">
<option value="" selected="selected" disabled="disabled">Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date">
<option value="" selected="selected" disabled="disabled">Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
</form>
JavaScript (index.js):
$(document).ready(function () {
$('.save').click(function (event) {
var $row = $(this).parents('tr');
var acct = $row.find('td[name="account"]').text();
var date = $row.find('td[name="date"]').text();
var checked = $row.find('input[name="selected"]').is(':checked');
var currency = $row.find('input[name="currency"]').val();
var datepicker = $row.find('input[name="datepicker"]').val();
var notes = $row.find('textarea[name="notes"]').val();
var paid = $row.find('input[name="paid"]').is(':checked');
var request = $.ajax({
type: "POST",
url: "update.php",
data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
success: function(data){
alert('Row successfully saved');
//window.location.href = window.location.href;
}
});
});
});
And this is my javascript that is run in my head tag in my main index.php page:
function showUser(collector,date) {
$('#billing_table').hide();
if (collector == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var newTableObject = document.getElementById('billing_table');
sorttable.makeSortable(newTableObject);
}
}
$.ajax(
"dropdown-display.php"
,{
data:{
q:collector,
data:date||undefined
}
}
).then(
function(responseText){
$("#txtHint").html(responseText);
sorttable.makeSortable($('#billing_table')[0]);
}
,function(error){
console.warn("something went wrong:",error);
debugger;
}
)
}
}
$(document).ready(function(){
$("#collector, #date").change(function(e){
showUser(
$("#collector").val()
,$("#date").val()
);
});
$("#collector").change(function(e){
$.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
$("#date .choice").hide();
$.each(data, function(key,row) {
$("#date option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
});
You can bind the event after successful response of ajax like that:
$(document).ready(function () {
$('.save').click(function (event) {
var $row = $(this).parents('tr');
var acct = $row.find('td[name="account"]').text();
var date = $row.find('td[name="date"]').text();
var checked = $row.find('input[name="selected"]').is(':checked');
var currency = $row.find('input[name="currency"]').val();
var datepicker = $row.find('input[name="datepicker"]').val();
var notes = $row.find('textarea[name="notes"]').val();
var paid = $row.find('input[name="paid"]').is(':checked');
var request = $.ajax({
type: "POST",
url: "update.php",
data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
success: function(data){
alert('Row successfully saved');
$('#chdir select').bind('change', getDirs); // this is use for example like change of select
}
});
});
});
function getDirs(){
//any functionality you want
}
You need to send the filters (in your Ajax call) as parameters to the page that gets the result. You could name them collector_sel and date_sel.
Once the update has been completed, you must return these parameters.
For example, you could return them in the same GET string you use for window.location. href.
window. location. href = "index.php?collector_sel=abc&date_sel=bcd"
Then on the page you initially load it compares the filter values to select them again.
<form name="testForm" action="">
<select id="collector">
<option value="">Collector Name</option>
<?php
$selected = "";
foreach($collect->fetchAll() as $name) {
if (isset($collect_sel)){
if (strpos($_GET['collect_val'],$name['Collector Name'])==0)
$selected = "selected";
}
} ?>
<option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"
selected="<?php echo $selected; ?>" ><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
// ....
</form>

Return javascript output for option select

I'm working on these codes for awhile and need some help. Basically, I'm trying to get the result or output of the script and put it in between the option select as shown here:
<select class="form-control" name="property_list">
*insert output javascript here
</select>
Below is the complete script. Would this method be possible?
<script>
$(document).ready(function(){
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log('Done: ', responseData);
}).fail(function() {
console.log('Failed');
});
});
});
</script>
<div class="input-group mb-3">
<span class="input-group-addon gi data-gi-size gi-user-add"></span>
<select id="client-list" name="client-list">
<?php
$sql = "SELECT `id`, `email`
FROM `clients` ORDER BY `id` ASC";
$result = $DB_CON_C->query($sql);
if($result !== false) {
$data_row = '<option>New Client</option>' . "\n";
foreach($result as $row) {
$data_row .= '<option>' .$row['email'] . '</option>' . "\n";
}
}
unset($row);
echo $data_row;
?>
</select>
</div>
<select class="form-control" name="property_list">
*insert output javascript here
</select>
Use .html() to add returned data to the select, in your done function get select by name and add the data. This will work if the returned data is in the following format:
<option value="1">1</option>
<option value="2">2</option>
jQuery
$(document).ready(function () {
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log(responseData);
var data = JSON.parse(responseData);
$('select[name="property_list"]').html(data);
}).fail(function() {
console.log('Failed');
});
});
});
Loop through your response data and append options to your property list like so:
$(document).ready(function(){
$("#client-list").on('change', function postinput(){
var matchvalue = $(this).val(); // this.value
$.ajax({
url: 'sql/client-to-property.php',
data: { matchvalue: matchvalue },
type: 'post'
}).done(function(responseData) {
console.log('Done: ', responseData);
var data = JSON.parse(responseData); // Assuming response data is a JSON string
data.each(function(i, property) {
$("input[name=property_list]").append("<option />").text(property);
});
}).fail(function() {
console.log('Failed');
});
});
});
The options will need values as well so you can add that attribute to the options too:
$("input[name=property_list]").append("<option />").attr('value', property).text(property);

Populate select box when document load

im trying to populate a select box from values in my database after the document load, or ready. I'm new to ajax and jquery, Can someone help find what's wrong to my code?
<select class="form-control sec" id="sec" name="sec">
<option value="sec">Section</option>
</select>
here's my ajax code.
function loadselectbox(){
var fac_code = $("#faculty_code").val();
$.ajax({
type: 'POST',
url: 'getrecords.php',
data: {
"load": 1,
"fac_code": fac_code
},
dataType: 'json',
success: function(data)
{
var select = $("#sec"), options = '';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'>";
}
select.append(options);
}
});
}
here's my getrecords.php
if (isset($_POST['load'])) {
$fac_code = $_POST['fac_code'];
$select = mysqli_query($con,"SELECT * FROM tfile WHERE faculty_code = '$fac_code'");
while ($row = mysql_fetch_array($select)) {
$result[] = array(
'section' => $row['section'],
'subj_descr' => $row['subj_descr']
);
}
echo json_encode($result);
}
i call the function in document.ready
$(document).ready(function() {
loaddata();
loadselectbox();
});
Try this:
$(document).ready(function(){
var fac_code = $("#faculty_code").val();
$.ajax({
url: 'getrecords.php',
type: 'POST',
data: {
"load": 1,
"fac_code": fac_code
},
success: function(response){ // response contains json object in it
var data = JSON.parse(response);
var options = '<option value=""></option>';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'> +data[i].subj_descr+ </option>";
}
$("#sec").html(options); // It will put the dynamic <option> set into the dropdown
}
});
});

Categories

Resources