How can I bind Jquery Ajax Json Reponses to a dropdown? - javascript

I'm trying to populate Json response from an Ajax call to a drop down and bind Name and UserID in a dropdown. Dropdown values all shows undefined. What I'm doing wrong here? Can you please help?
Dropdown DIV -
<div class="row form-group spacer">
<div class="col-md-12">
<div class="col-md-12">
#Html.Label("Recipients")
<select id="commentrecipients" class="dirtyignore" name="commentrecipients"></select>
</div>
</div>
</div>
Ajax Call -
$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
success: function (data) {
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].UserID + '">' + data[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});
Json Response -
data = "[{"SecurityGroupID":31,"SecurityGroupName":"Permission Testers","UserID":30,"Name":"Dawn Test'Neil"},{"SecurityGroupID":31,"SecurityGroupName":"Permission Testers","UserID":213,"Name":"Dawn 2 Bates"}]"

You need to parse the JSON data to get the object and then loop it.
ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
success: function (data) {
let response = JSON.parse(data);
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < response.length; i++) {
s += '<option value="' + response[i].UserID + '">' + response[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});

Try adding dataType: "json" and remove the "data:" ... something like this:
$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
dataType: "JSON",
success: function (data) {
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].UserID + '">' + data[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});

Please try using the camel case property name:-
s += '<option value="' + data[i].userID + '">' + data[i].name + '</option>';

$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var s = '<option value="-1">Please Select a Recipient</option>';
s += '<option value="' + val.UserID + '">' + val.Name + '</option>';
}
$("#commentrecipients").html(s);
}
});

Related

Jquery get this.value from an input field on the click of a button

How can I get the value from an input field when I click the button using jquery?
Below is my Jquery code :
asset_status_list = '';
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>operations/asset_status",
dataType: "JSON",
success: function (response) {
for (i = 0; i < response.length; i++) {
asset_status_list = '<tr><td >' + response[i].job_card_no + '</td><td >' + response[i].number + '</td><td>' + response[i].type + '</td><td ><input type="text" name="view_more_id" class="view_more_id' + response[i].asset_id + ' btn btn-default" id="view_more_id" value="' + response[i].asset_id + '"/><button id="view_more_link" class="view_more_link' + response[i].asset_id + '"><i class="glyphicon glyphicon-zoom-in "></i>View More</button></td></tr>';
$('#asset_status_tr').append(asset_status_list);
$("#asset_status_tr").on("click", ".view_more_link" + response[i].asset_id, function () {
console.log(response);
var asset_id = this.value;
alert(asset_id);
});
}
$('#asset_table_status').DataTable({});
},
error: function (response) {
}
});
I want to get the value of the input field name view_more_id .
Is this the answer you are looking for ? var asset_id = $( "#view_more_id" ).val();

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN
function createCheckBoxPlatform(data) {
var platform = "";
$.each(data, function (i, item) {
platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' + getOS();
});
$('#platform').append((platform));
}
function getOS() {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
success: function (data) {
var os = '<div>';
$.each(data, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
return os;
}
});
}
I think you have to turn around your logic. The createCheckBoxPlatform loop will have completed before the getOS() ajax call returns, unless it's a synchronous call.
You could split the functions into pieces, gather the getOS data for each data point you have, then construct the checkboxes when your ajax call returns.
You can make your ajax call async and have to make no changes to your current logic. But your execution will stop till you don't get the callback to your ajax call.
function getOS() {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
async: true,
success: function (data) {
var os = '<div>';
$.each(data, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
return os;
}
});
}
the first "A" in AJAX stands for "Asynchronous" that means, it is not executed right after it has been called. So you never get the value.
Maybe you could first, get the os list and then output what you need, like this:
function createCheckBoxPlatform(myDatas) {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
success: function (osList) {
var os = '<div>';
$.each(osList, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
$.each(myDdatas, function (i, item) {
platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>'+os
});
$('#platform').append((platform));
}
});
}

Populate a Dropdown Menu with JSON Data

Attempting to populate a drop down menu with JSON data but cant quite figure out what I am doing wrong.
JSON Data
{"dropdownValue1":"1x1","dropdownDisplay1":"1x1","dropdownValue2":"1x2","dropdownDisplay2":"1x2","dropdownValue3":"1x3","dropdownDisplay3":"1x3","dropdownValue4":"1x4","dropdownDisplay4":"1x4","dropdownValue5":"1x5","dropdownDisplay5":"1x5","dropdownValue6":"1x6","dropdownDisplay6":"1x6"}
Java/HTML
<script type="application/javascript">
$(function(){
$("select#size").change(function(){
$.getJSON("getDropdown",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + i + '">' + j[i] + '</option>';
}
$("select#size").append(options);
})
})
}) </script>
<div class="input select orderBoxContent">
<select name="size" id="size">
</select>
</div>
Actual JSON request
function getDropdown()
{
var people_no = $('#howmanypeople').val();
$.getJSON("../../getdata.php?getDropdown=yes&people_no="+people_no, function(response) {
$('#getDropdown').html(response.getDropdown);
});
}
Cheers
Ryan
Your JSON is an object but you are itterating it like an array.
var i;
for (i in j) {
if (j.hasOwnProperty(i)) {
// i = 'dropdownValue1'
// j[i] = "1x1"
// but the order is unknown
options += '<option value="' + j[i] + '">' + j[i] + '</option>';
}
}
$(function(){
$("select#size").change(function(){
$.getJSON("getDropdown",{id: $(this).val(), ajax: 'true'}, function(j){
var i;
for (i in j) {
if (j.hasOwnProperty(i)) {
// i = 'dropdownValue1'
// j[i] = "1x1"
// but the order is unknown
options += '<option value="' + j[i] + '">' + j[i] + '</option>';
}
}
$("select#size").append(options);
})
})
})

Call function after some period time

I'm having a problem and don't know how to solve it. I have two functions in Javascript, both are called via AJAX, first function get values and insert records in DB and second function reads from DB and show the results. Since first function get values remotely sometimes response times are larger than second function and for that reason second function executes before first. What I need is to call buildTablesFromDB() only if AJAX call for buildClassification() is done. This is how my code looks like:
$(document).ready(function() {
function buildTablesFromDB() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/reader.php",
success: function(data) {
$("#clasification-data").html();
if (data.response === false) {
$(".alert").show();
$(".close").after(data.error);
} else {
if (data.html_content.position.length != 0) {
$("#clasification-holder").show();
var iterator = data.html_content.position;
var tr = "";
$.each(iterator, function(key, value) {
tr += "<tr>";
tr += '<td><img src="' + value.team_image + '" alt="' + value.team_name + '" title="' + value.team_name + '"> ' + value.team_name + '</td>';
tr += '<td>' + value.team_jj + '</td>';
tr += '<td>' + value.team_jg + '</td>';
tr += '<td>' + value.team_jp + '</td>';
tr += '<td>' + value.team_difference + '</td>';
tr += '<td><span class="glyphicon glyphicon-play"></span><span class="glyphicon glyphicon-stop"></span></td>';
tr += '</tr>';
});
$("#clasification-data").html(tr);
}
}
},
error: function() {
request.abort();
}
});
}
function buildClassification() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
// some error
}
},
error: function() {
request.abort();
}
});
}
window.setInterval(function() {
buildClassification();
}, 1800000); // Updates table results each 30 minutes
window.setInterval(function() {
buildTablesFromDB();
}, 1800000); // Updates table results each 30 minutes
buildClassification();
buildTablesFromDB();
});
How I can get this done?
you can call buildTablesFromDB() in the callback method of buildClassification()
e.g.
....
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
//
}else{
buildTablesFromDB();
}
},

Data available only after alert [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery: Return data after ajax call success
I wrote a script which adds a new div container to the said with the a select field inside. The data for the select field is loaded with an ajax request before. But for some reason the fields are only visible when I output something with alert().
var o = '';
$.ajax({
type: 'post',
dataType: 'json',
url: webroot + 'items',
success: function(data) {
$.each(data, function(index, value) {
o += '<option value="' + index + '">' + value + '</option>';
});
}
});
var l = parseInt($('.items .item').length);
var h = '<div class="item"><span class="bold">Item ' + (l + 1) + '</span><select id="ItemName" name="data[Item][name]">' + o + '</select></div>';
I have actually no idea how to solve this problem. Can you help me?
Ajax is asynchronous. Move all of your code into the success function, and it will work. The reason it works with alert is because the alert allows some time to get the AJAX result.
$.ajax({
type: 'post',
dataType: 'json',
url: webroot + 'items',
success: function(data) {
var o = '';
$.each(data, function(index, value) {
o += '<option value="' + index + '">' + value + '</option>';
});
var l = parseInt($('.items .item').length);
var h = '<div class="item"><span class="bold">Item ' + (l + 1) + '</span><select id="ItemName" name="data[Item][name]">' + o + '</select></div>';
}
});
Your code doesn't actually do anything other than load some html into a variable though. So whatever you were doing with "h", do it in the success function.

Categories

Resources