Dropdown populated througn javascript is showing each character as a dropdown option - javascript

I am using this javascript method to populate dropdown-
<script type="text/javascript">
function openPopup()
{
$("#wrapper").html('');
$.get('getClanLeads', function(data){
var options = '';
$.each(data, function(i,data){
options +='<option value="'+ data +'">' + data + '</option>';
});
$("#wrapper").append('<select>' + options + '</select>');
alert(data);
location.href = "#divModalDialog1";
});
}
</script>
But this is showing the data's characters as the options of the dropdown. Not the data values fetched from the database.
The data is returned from server as--
[{"user_id":3},{"user_id":4}]
But it is added to dropdown as '[', '{', '"', 'u', 's', 'e', 'r', ...

The data isn't being interpreted as JSON. Changing the outer call to:
$.get('getClanLeads', function(data){
// ...
}, 'json');
should help.
After that, you need to be careful about which part of each element you use:
$.each(data, function(i,item){
options +='<option value="'+ item.user_id +'">' + item.user_id + '</option>';
});

Related

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

Why always getting last row from json array result when iterate through with Jquery

I have json data in this structure
here is my json code
https://jsonblob.com/309e8861-7f26-11e7-9e0d-cf3972f3635e
and here is my jquery code example
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
$.each(data, function(index, val) {
$("#result").html("<p>" + val.name + "</p>");
});
});
});
HTML file
<button id="getJsonData">Load role list</button>
<div id="result"></div>
I don't get this, I get every value from json in console when do console.log, but when use html method to display result as html in screen it just showing last value from ending last json array. What is wrong here?
jquery .html always overrite previous html so we cant use html in loop section instead of that we can use append it simply append your p tag in result div
Instead of using this:-
$("#result").html("<p>" + val.name + "</p>");
use like this:-
$("#result").append("<p>" + val.name + "</p>");
You are overwriting the html with the code
$("#result").html("<p>" + val.name + "</p>");
Instead you can store the result in variable and then you write it to the element.Like this
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
var html = '';
$.each(data, function(index, val) {
html +="<p>" + val.name + "</p>";
});
$("#result").html(html);
});
});
Your code should be :
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
var listHtml="";
$.each(data, function(index, val) {
listHtml=listHtml+ "<p>" + val.name + "</p>";
});
$("#result").html(listHtml);
});
});
And Html should be same as your
<button id="getJsonData">Load role list</button>
<div id="result"></div>
Working example is here

how to append a html tag from an ajax call response

I have an ajax function :
$('#app-name').change(function () {//1
console.log("inside change");
var applname= this.value;
console.log(applname);
$.ajax({//2
url: 'foo',
method : 'GET',
dataType : "json",
contentType: "application/json",
data: {"AppID":"appname"},
success: function(data){
var order_data = data;
$('#foo-name').html('');
$.each(order_data, function(i, item) {//3
console.log(order_data[i]);
$('<option value='+ order_data[i] +'>'+order_data[i]).html('</options>').appendTo('#foo-name');
});//3
}
});//2
});//1
This function is doing everything else except appending value to the html.
Am i doing it wrong? Can you help solve this issues.
Place the closing </option tag in the jQuery object you create. Don't set it through the html() method. Try this:
$('<option value="' + order_data[i] + '">' + order_data[i] + '</option>').appendTo('#foo-name');
That said, you can also improve performance of your code by building the string in the loop and appending it to the select once, like this:
success: function(data) {
var options = '';
$.each(data.split(/\n/), function(i, item) {
options += '<option value=' + item.trim() + '>' + item.trim() + '</option>');
});
$('#foo-name').html(options);
}
Update You also need to split() the text you state that you're returning before looping through it.
Please use below code in your ajax success event.
success: function(data) {
var _html = '';
$.each(order_data, function(i, item) {
_html += '<option value='+ item +'>'+item+'</options>';
});
$('#foo-name').append(_html);
}

Dropdown populated using javascript showing only 'Undefined' in the dropdown options

I am using A javascript MEthod to populate Dropdown list as following but getting many 'Undefined' in my dropdown options-
<script type="text/javascript">
function openPopup()
{
$("#wrapper").html('');
$.get('getClanLeads', function(data){
var options = '';
$.each(data, function(i,data){
options +='<option value="'+ data.user_id +'">' + data.user_id + '</option>';
});
$("#wrapper").append('<select>' + options + '</select>');
alert(data);
location.href = "#divModalDialog1";
});
}
</script>
options +='<option value="'+ data.user_id +'">' + data.user_id + '</option>';
Try change
data.user_id
to
data.user_id.value

Parsing JSON data into SELECT prints UNDEFINED

My JSON being sent from the server is like this:
data[
{"userFullName":"Tim, Bill","id":"LOt3","organisation":"FAP","loginSystem":"A","userId":0},{"userFullName":"Bruce, David","id":"LNA","organisation":"ES","loginSystem":"A","userId":0}
]
In the success of my AJAX call,I am handling the data as follows :
success: function (data) {
javascript: console.log('data' + data);
$.each(data, function(key, value) {
javascript: console.log('id' + value.id);
$('#selectStaff').append('<option value="' + value.id+ '">' + value.userFullName + '</option>');
});
}
selectStaff is the ID of the SELECT control...
The SELECT control is drawing with 'undefined' populated in the drop down.
The console.log('data' + data) prints the following line:
data[{"userFullName":"Tim, Bill","id":"LOt3","organisation":"FAP","loginSystem":"A","userId":0},{"userFullName":"Bruce, David","id":"LNA","organisation":"ES","loginSystem":"A","userId":0}]
However, the line javascript: console.log('id' + value.id) prints out 'UNDEFINED'
Would someone please describe the correct syntax to me?
Error in your code val.id
Working Fine
Fiddle
Script
var user=[{"userFullName":"be, apple","id":"xdsd3","organisation":"FL ","userId":0},{"userFullName":"Mack, David","id":"lol323","organisation":"ES","userId":0}]
$.each(user, function(key, value) {
console.log('id' + value.id);
$('#selectStaff').append('<option value="' + value.id + '">' + value.userFullName + '</option>');
});

Categories

Resources