Parsing JSON data into SELECT prints UNDEFINED - javascript

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

Related

How to add multiple variables in .val() jquery function

I am adding data using AJAX then appending that data in dropdown, after that I am using .val().trigger() jQuery function to get that newly added data on the top of drop down by passing multiple variables in .val() function; val function is accepting one variable and working fine but I want to add multiple variables in val() function.
JS CODE
success: function(data) {
toastr['success']("<?php echo lang('add'); ?>", "Customer Device Added");
setTimeout(function() {
const obj = JSON.parse(data);
// console.log(data)
// console.log(obj)
jQuery('#customer_device').append('<option value="' + obj[0].device_brand + ' ' + obj[0].device_model + ' ' + obj[0].device_imei + '">' + obj[0].device_brand + ' ' + obj[0].device_model + ' ' + obj[0].device_imei + '</option>');
jQuery('#customer_device').val(obj[0].device_brand).trigger("change");
$('#customer_device_modal').modal('hide');
}, 500);
}
Here I am appending these data:
obj[0].device_brand, obj[0].device_model, obj[0].device_imei
I want to trigger these all variables in .val() function to get these in dropdown at top; as I am getting one variable in val function. Thank you

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

Update: How do I dynamically populate a list with data from a JSON file?

I want to dynamically populate a list with elements from a JSON file. The idea is to switch the test_ID in the list with the actual object from the JSON file. How do I do this?
JSON file
[
{
"id": "a",
"test": "Java",
"testDate": "2016-08-01"
},
{
"id": "b",
"test":"JavaScript",
"testDate": "2016-08-01"
}
]
jQuery
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
});
$("#test_ID").empty(); //emtpy the UL before starting
$.each(arr_json, function(i, v, d) {
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
});
}
});
});
HTML
<li id="test_ID"></li>
I do receive a couple of errors. The Line:
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
gives the following error: invalid number of arguments and unclosed String literal.
I am also unsure of how to identify to specific elements in the JSON file.
Update
I would like if the list element was in this format "Java 2016-08-01" and "JavaScript 2016-08-01". Thank you!
You have a couple of errors in your javascript. See the corrected version below:
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
$("#test_ID").empty(); //emtpy the UL before starting
// **************** correction made to the line below ***********************
$.each(result, function(i, v, d) {
// **************** correction made to the line below ***********************
$("#test_ID").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>'); // correction made here
});
}
});
});
I did a quick fiddle. I don't quite understand what you're doing with v.test being unmarked inside the HTML tags so I did not include it. I used minimal JQuery to avoid complexity.
https://jsfiddle.net/ndx5da97/
for (record in data) {
$("#test_ID").append('<li id="' + data[record].id + '">' + data[record].testDate + '</li>');
}
Hope this helps!

TypeError: a is undefined in jquery at the first line?

So, in my code, when I press my #jsonclick button, it activates my script which populates a table with information from a JSON page. The problem I am having is that I am getting a TypeError: a is undefined, and I have no idea why.
Here is my code:
jQuery function
$("#clickjson").click(function () {
$.getJSON("gmessagegroup.php?gid=" + $('#gbox').val(), function (data) {
$.each(data.messages, function (key, val) {
if (data.messages[key].clientmessageid != undefined) {
console.log(data.messages[key].clientmessageid + ":" + data.messages[key].from + " - " + data.messages[key].content);
$("#messages tbody tr:last").after('<tr><td>' + data.messages[key].clientmessageid + '</td><td>' + escapeHtml(data.messages[key].from).replace("https://bn1-client-s.gateway.messenger.live.com/v1/users/ME/contacts/8:", "") + '</td><td id=' + data.messages[key].clientmessageid + ' contenteditable="true">' + escapeHtml(data.messages[key].content) + '</td></tr>');
}
});
});
setTimeout(function () {
var message_status = $("#status");
$("td[contenteditable=true]").blur(function () {
var field_userid = $(this).attr("id");
var value = $(this).text();
$.post('groupedit.php', field_userid + "=" + value, function (data) {});
});
}, 1000);
});
The code is getting the value of the selected item in a dropdown select. I tried putting and alert in and it is putting out the correct value that is being pushed out to the PHP. I am unsure of where the TypeError comes into play, all I know is that when I remove ?gid=" + $('#gbox').val() from the end of the php, the error goes away. Problem is, I need that for the php to work. Can somebody please tell me why this is happening?
Thanks.
Actually in your json response messages is not found thats why it is responding as a is undefined check if you json data has messages or not like,
if(data && data.messages.length) // check for messages
$.each(data.messages, function (key, val) {
if (data.messages[key].clientmessageid != undefined) {
...
}
});
}
Snapshop

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

Categories

Resources