Add ajax return value to selectbox? - javascript

I am trying to insert a value from my database to select box using it's ID. this my code for that
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$("#brnch_name").val(segments[17].trim());
}
});
My value has returned successfully. But, it shows nothing to my select box. Can anyone help me please?

You need to add proper html to select. Something like
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>"
}
And then $("#brnch_name").html(html).
For this example, I assume you are getting response in json format

Here is my solution:
$("#brnch_name").empty(); //clear the drop down box
for (var i=0;i<segments.length;i++)
{
html="<option value=\""+segments[i]+"\">"+segments[i]+"</option>";
$("#brnch_name").append(html);
}

You can loop the response and append to select with $('#branch_name').append($('<option>', { value: item.value, text : item.text })); here value is the value of option and text is text to be displayed on dorpdown.
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (i, item) {
$('#branch_name').append($('<option>', {
value: item.value,
text : item.text
}));
});
});
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>

Use $.each like below:
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (key, value) {
$("#brnch_name").append($("<option></option>").val(segments[key].trim());
});
}
});

You need to iterate through each branch names from response and append the same as individual <option> tags. However you have already got several solutions for the same, while mine uses simple string replace.
/* this is only relevant script */
var response = 'Branch 1,Branch 2,Branch 3,Branch 4';
$('<option>' + response.replace(/\,/g, '</option><option>') + '</option>').appendTo('#branch_name');
/*in-case you wish to show a default selection */
$('#branch_name').prop('selectedIndex', 3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="branch_name"><option value="0">Select branch Name</option></select>

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);
}
});
});

Asp.Net Core - Return values from the controller and put the values ​into the inputs by Ajax?

I have a drop down list and I want the value to be sent to the controller when an option is selected,replaceing the returned values ​​in the desired inputs
Html Inputs :
<input type="text" class="form-control js-inputs" id="microchipcode">
<input class="form-control js-inputs" id="fa-horse">
<input type="text" id="fa-fatherhorse" class="form-control js-inputs">
Html DropDown:
$('.js-selected-item').change(function () {
let Value = $(this).val();
$.ajax({
data: { value: Value },
Url: "/Horse/GetHorseByMcode",
type: "post",
success: function (data) {
}
});
});
Controller :
public async Task<IActionResult> GetInfoHorse(string value)
{
var horse = await _coach.GetHorseByMcode(value);
if (horse != null)
{
return Json(horse);
}
return NotFound();
}
Query :
public async Task<Horse> GetHorseByMcode(string value)
{
return await _context.Horses.SingleAsync(h => h.MicrochipCode == value.Trim());
}
If you want to put a value into an input via js, add an ID to the inputs and do the following:
JS:
document.getElementById('//inputId').value = '';
Jquery:
("#//inputId").val("");
How do I access the data inside the object?
You can check the request and response in f12 developer tool Network tab, like below.
and implement frontend code to populate input field(s) in ajax success callback function based on your actual returned data.
For example:
success: function (data) {
$("#fa-fatherhorse").val(data.fatherHorse);
//populate other inputs based on your actual returned data
How to replace Drop Down list ?
If you want to dynamically set the selected value/option of the dropdown, you can try:
$("#dropdown_id_here").val(value_of_selected_option);
If you want to dynamically append <option> to your dropdown, you can try:
var newoption = "<option value='" + option_val + "'>" + option_text + "</option>";
$("#dropdown_id_here").append(newoption);

Javascript + PHP - Populate select based on radio option, but grab the result from database

Right now I am using a static array in my javascript and I would like to change it to get the info from my MariaDB table. I have one radio select (yes/no) that should determine which entries are selected to populate the select field, if yes, get the DB results for A, B, C, if no, get X, Y, Z.
<script type="text/javascript">
$(function() {
var primaryDisposition = {
1: ['A', 'B', 'C'],
2: ['X', 'Y', 'Z']
};
$('#radioDispositionGroup input[type=radio]').click(function(){
var options = '<option disabled selected>Choose one</option>';
$.each(primaryDisposition[$(this).val()] || [], function(i, v) {
options += '<option>' + v + '</option>';
});
$('select[name="selectDisposition"]').html(options);
});
});
</script>
EDIT:
I switched to using ajax, even though fetch would work just as well.
I do have a question, the following does get the data I want, but I am not sure on the best way to make it
so when I click on the radio Yes it will populate the select field.
$(function() {
$.ajax({
method: 'GET',
url: "/dispositions",
success: function(data){
let primaryDisposition = data;
$('#radioDispositionGroup input[type=radio]').click(function(){
let options = '<option disabled selected>Choose one</option>';
$.each(primaryDisposition, function(i, v) {
options += '<option value="'+ v.id +'">' + v.description + '</option>';
});
$('select[name="selectDisposition"]').html(options);
});
console.log('Success0 '+ data[0].description); //using data[0] so I can see the test data
}
});
});
If you want to use something like fetch to get a javascript array to work with like you are doing on your code then you can use this example for your php page: JSON encode MySQL results
Your fetch code would look something like:
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function(data) {
// Your code for handling the data you get from the API
let primaryDisposition = JSON.parse(primaryDisposition)
$('#radioDispositionGroup input[type=radio]').click(function(){
var options = '<option disabled selected>Choose one</option>';
$.each(primaryDisposition[$(this).val()] || [], function(i, v) {
options += '<option>' + v + '</option>';
});
$('select[name="selectDisposition"]').html(options);
});
})
.catch(function() {
// This is where you run code if the server returns any errors
});

TypeError: $(...).val(...).html is not a function

I am getting json array from Ajax response, i am trying to add this in drop-down but I am getting error above error.
JSON array after stringyfy contain below array.
[{"ID":"1","NAME":"Nevpro"},{"ID":"9","NAME":"Tushar"}]
<html>
<select name id='sel'>
</select>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(
function() {
$('.filter-dropdown').change(function() {
var lan = this.value;
//alert(lan);
//alert(lan)
$.ajax({
url: "http://10.10.1.84/services/request.php",
dataType: "json",
type: "POST",
data: {lan : lan},
success: function(data){
var data1=JSON.stringify(data);
alert(data1);
$.each(data1,function (key,value) {
alert(key);
$("#sel").append($('<option></option>').val(value.ID).html(value.NAME));
});
}
});
});
});
</script>
You can define the value and text as an object.
$("#sel").append(
$('<option></option>',{
value : value.ID,
text : value.NAME
})
);
UPDATE : Although there is one more bug, you are iterating over the stringified data so replace it with the object(which is the actual issue lies in your code).
$.each(data,.....
//-----^^^^------
$.each(data1,function (key,value) {
alert(key);
$('#sel').append('<option value='+value.ID+'>'+value.NAME+'</option>');
});
You need not add $ inside append again. You can add options like this inside your loop.
I think this shoud solve your problem
var optionTemp = document.createElement('option')
for (i in data1) {
var option = optionTemp.cloneNode();
option.value = data1[i][ID];
option.text = data1[i][NAME];
$('#sel').append(option);
}

Issue not having a selected default option while populating select with ajax

I'm having a problem not being able to have a default selected option when i fill the select box with ajax call, i have the value, but not a default one, I want that the default one will be the first value i get from the call;
my HTML is (we will work on select2):
<div class="containerdiv">
<select class="select1" name="dettaglio1">
</select> <select class="select2" name="dettaglio2">
</select> <select class="select3" name="dettaglio3">
</select>
</div>
while the ajax call is that (Comments are for you):
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
and my html after the call is(F12) :
<div id="select-4-button" class="ui-btn ui-icon-carat-d ui-btn-icon-right ui-corner-all ui-shadow">
<span class="select2"> </span>
<select class="select2" name="dettaglio2">
<option value="0">option1</option>
<option value="1">option2</option>
<option value="2">option3</option>
<option value="3">option4</option
><option value="4">option5</option>
</select></div>
Is the problem on span element? and why it's blank ?
Select the default value once all the options are loaded. Check below
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$('select[name=dettaglio2]').val($('select[name=dettaglio2] option:first').val());
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
$(".select2")[0].selectedIndex = 0;
You should try this when your select tag is already populated/.
Thank to Pugazh I modified his answer and came to this working solution:
$("#select-4-button").children("span").html($('select[name=dettaglio2] option:first').text());
the full code:
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$("#select-4-button").children("span").html($('select[name=dettaglio2] option:first').text());
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
I answered because is more clear the solution, but thumbs up his answer and comments that helped me.
(I've thumbed up everyone that helped, thanks a lot) ;)
Use following once your options loaded :
$('.select2 option:eq(1)').prop('selected', true)
Here 1 is index.you can set default value by index easily.
Change your success part to below code:
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$('.select2 option:eq(1)').prop('selected', true)
},
If there is 2 .select2 class then use index for .select2
( Check This Link for same)

Categories

Resources