JSON Data is not populated into the Dropdownlist - javascript

I have the following code in my js file. When i alerted and checked the value of key, its being coming from JSON response, but when i checked my val, its shown as [object object]. So i tried using val.value, the value comes to be undefined.
FYI: I am getting the correct response from my controller through Json, i have checked it, all i want to know is how to populate text value into the dropdown.
$(document).ready(function () {
BindTitle();
});
function BindTitle() {
$.ajax({
"url": "/Admin/GetTitleList/",
"type": "get",
"dataType": "json",
"success": function (data) {
var appenddata;
$.each(data, function (key, val) {
appenddata += "<option value = '" + key + " '>" + val.text + " </option>";
});
$("#TitleId").html(appenddata);
}
});
}

Your way of building dropdown wont work on ie8
try
$.ajax({
url: "/Admin/GetTitleList/",
type: "GET"
success: function (data) {
var items = $('#id of your dropdown');
items.empty();
$.each(data, function (i, drddata) {
items.append($('<option/>', { value: drddata.Value, html: drddata.Text
});
});
},
error: function () {
}
});

Related

ASP.NET MVC - After HTML append with Jquery the DropDownList value comes as undefined

I have two dropdownlist and when I change the value of the first one with refreshes the value of the second one with the following code:
function FillBooks(val) {
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$("#DDL_TIPO").empty();
$.ajax({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: "POST",
dataType: "JSON",
data: { value: CategoryId },
success: function (data) {
var markup = "<option value='0'>Selecione um Tipo</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].value + ">" + data[x].Text + "</option>";
}
$("#DDL_TIPO").html(markup).show();
}
});
}
P.S - The data comes from the controller which is not relevant for the exemple that I am showing.
After this when I try to get the value of the Second dropdownlist it comes as undefined.
I tested before this jquery code and it gives me the value of the dropdownlist, it just doesn't give when I get this function to work on it.
Try this:
<script>
function FillBooks(val)
{
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$.ajax
({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: { value: CategoryId },
success: function(result)
{
$("#DDL_TIPO").html("");
$.each($.parseJSON(result), function(i, tipo)
{
$("#DDL_TIPO").append($('<option</option>').val(tipo.Value).html(tipo.Text))
})
},
error: function()
{
alert("Whooaaa! Something went wrong..")
},
});
}
</script>

How to put JSON data into a HTML div?

Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.
function showEspece(espece, categorie, object) {
$.ajax({
type: 'POST',
url: 'getespece.php',
data: {
espece: espece,
categorie: categorie
},
dataType: 'json',
success: function(data) {
console.log(data);
$('#output').html(data); //what i try to do but don't work
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
<div id="output"></div>
And here is what the variable data contains:
How can I show the variable's content in an HTML div - in a table particularly?
You can use pre tag to display JSON.
var data = {"NOMA":["Chachi","Rafiki","Chakra"],"SEXE":["F","M","F"],"DATENAISSANCE":["05-MAY-15","07-JAN-15","17-SEP-17"]};
$('pre').html(JSON.stringify(data, undefined, 2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>
Your data variable it's a JS object you need to convert it to string or the format you want to show it before calling $('#output').html(data).
You can do something like:
function showEspece(espece, categorie, object)
{
$.ajax({
type : 'POST',
url: 'getespece.php',
data: {espece: espece, categorie: categorie },
dataType: 'json',
success: function(data)
{
console.log(data);
data = JSON.stringify(data)
$('#output').html(data); //what i try to do but don't work
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
as your json data children are array you can use $.each function:
Example:
var noma = data.NOMA;
var html_append = '';
$.each(noma, function(key,value) {
html_append += value +'<br>';
});
$('#output').html(html_append);
The same code you can use for also data.DATENAISSANCE and data.SEXE
Since your data returned is already in a JSON format, i suggest you to use $.getJSON and change your $_POST by $_GET variables in your getespece.php.
Also, your JSON Objects seems to be kind of not formatted correctly.. If you want to display your "especes" in an HTML table, the right JSON format could be something like this:
{
"Columns": [
"DateDeNaissance",
"Nom",
"Sexe"
],
"Especes": [{
"DateDeNaissance": "05-MAY-15",
"Nom": "Chachi",
"Sexe": "F"
}, {
"DateDeNaissance": "07-JAN-15",
"Nom": "Rafiki",
"Sexe": "M"
}, {
"DateDeNaissance": "17-SEP-17",
"Nom": "Chakra",
"Sexe": "F"
}]
}
Once you have this output from your PHP, change your JS to this:
$.getJSON("getespece.php", {
espece: espece,
categorie: categorie
})
.done(function(json) {
// Build the html Table
var html = "<table>\n";
html += "<thead>\n";
html += "<tr>\n";
// Columns
$.each(json.Columns, function(k, value) {
html += "<th>" + column + "</th>\n";
});
html += "</tr>\n";
html += "<tbody>\n";
// Rows
$.each(json.Especes, function(column, values) {
html += "<tr>\n";
// Cells
$.each(values, function(k, val) {
html += "<td>" + val + "</td>\n";
});
html += "</tr>\n";
});
html += "</tbody>\n";
html += "</table>\n";
$("#output").html(html);
});
var data = {
DATENAISSANCE: [...],
...
}
var root = document.getElementById("output");
var table = element("table");
root.appendChild(table);
var dataName;
for (dataName in data) {
if (data.hasOwnProperty(dataName)) {
var row = element("tr", element("th", dataName));
data[dataName].forEach(function (dataValue) {
row.appendChild(element("td", dataValue));
});
table.appendChild(row);
}
}
// Create a convenient function `element` which creates an element and sets its content
function element(nodeName, content, attributes, eventListeners) {
var node = document.createElement(nodeName);
appendChildren(node, content);
return node;
}
function appendChildren(node, content) {
var append = function (t) {
if (/string|number/.test(typeof t)) {
node.innerHTML += t;
} else if (t instanceof HTMLElement) {
node.appendChild(t);
}
};
if (content instanceof Array) {
content.forEach(function (item) {
append(item);
});
} else {
append(content);
}
}

Binding dropdown list using ajax and jQuery

I would like to bind the data from splunk to a dropdown list.
The servlet return a JsonString by gson
Gson gson = new Gson();
String jsonString = gson.toJson(arrays);
resp.getWriter().write(jsonString);
In the jsp, ajax was used to get back the jsonString and blind in drop down list.
$(document).ready(function() {
$.ajax({
type: "POST",
dataType : "json",
url : "../getName",
success : function(data) {
console.log("success to return name");
if (msg) {
alert("Somebody" + name + " was added in list !");
location.reload(true);
} else {
alert("Cannot add to list !");
}
$.each(objdata["wlsDomain"], function(i, val) {
jQuery('#DropdownList').append('<option value="' + val.name + '</option>');
});
};
)};
)];
It said $(...).ready is not a function. If I change the "$" to "jQuery", then there is no warning. However, binding is failed.
Then I have also tried the below code for knowing whether the ajax is workable.
And it showed "Fail". Therefore, the ajax is not workable.
jQuery(document).ready(function() {
var promise =jQuery.ajax({
type: "POST",
url: "../getName",
dataType: "json"
});
promise.fail( function() {
window.alert("Fail!");
});
promise.done( function() {
window.alert("Success!");
});
May I know what's wrong with this?
And how can I bind the name get from splunk to a dropdown list?
Thanks!
Try the following code:
$(document).ready(function () {
var $el = $('#DropdownList');
var url = "../getName";
$.getJSON(url, {}, function (data) {
$el.empty(); // remove old options
$.each(data, function(index, obj) {
$el.append($("<option></option>")
.attr("value", obj.name).text(obj.name));
});
} );
});

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

jquery binding a key value pair

Hi I am using spring mvc in my application. The service returns a json response like,
[{"Key1": "value1"}]
I need to bind only the value part from the response to a drop down list in a jquery dialog. I use an AJAX call to get the list of items and to bind it. But it binds the whole row in the drop down list, not the value.
The code I use for binding the response is:
<script type="text/javascript">
$(function() {
$.ajax({
type : "GET",
url : "countries/getname",
contentType : "application/json; charset=utf-8",
dataType : "json",
success : function(msg) {
alert("MSG:"+msg);//this gives {"Key1": "value1"}
$.each(msg,function(key, val) {
alert("KEY::"+key); //key is returned as 0
alert("VALUE::"+val); //value is returned as{"Key1": "value1"}
$('<option />', {value: key, text: val}).appendTo("#sampleResp");
});
},
error : function() {
$("#sampleResp").get(0).options.length = 0;
$("#sampleResp").get(0).options[0] = new Option("None", "None");
}
});
});
</script>
The value field is the item and it has the following form:
{ "Key1": "value1"}
SampleResp is the ID of the dropdownlist.
The jsp code looks like this:
<div>
<form:select path="sampleResp" cssClass="w200">
</form:select>
</div>
How to extract only the value part from the response and bind it into the drop down using ajax call in jquery?
I can't test this code, becouse you didn't provide enough info (what is #sampleResp?, what is Option?, what is msg?)
My guess is:
new Option(item[0]);
if it doesn't work provide info for console.log(msg)
JavaScript has the eval() function that transforms the JSON text string into an object of the DOM, where you can access all the variables and their values​​.
On the other hand, if you're receiving that JSON string by calling via Ajax, just adding dataType:"json" option in the $.ajax() function will create automatically an object in the handler function.
$.ajax({
url:'someUrl',
dataType: 'json',
success: handleData
});
function handleData(jsonObj) {
var key1=jsonObj.key1;
//key 1 now is "value1"
}
http://api.jquery.com/jQuery.ajax/
In fact, you can also use the function $.getJSON() as a simple way for do the same
http://api.jquery.com/jQuery.getJSON/
Well so here is the solution,
success : function(msg) {
$.each(msg, function(index, elem) {
$.each(elem, function(key, value){
$('<option value="'+value+'">'+value+'</option>').appendTo($("#sampleResp"));
});
});
}
fiddle : http://jsfiddle.net/Bzf7j/
Working code here :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$.ajax({
url:'url_of_json_file',
dataType: 'json',
success: createDropDown
});
$.each(data[0], function(key, val) {
items.push('<option id="' + key + '">' + val + '</option>');
});
$("#dropDown").append(items.join(''));
});
</script>
</head>
<body>
All JSON values in drop down.
<select id="dropDown">
</select>
</body>
</html>
Assuming JSON content in file is of the below form:
[{
"Key1": "value1",
"key2":"value2"
}]
Working jsFiddle Demo
If you are getting this result in your alert:
alert(msg);
// {"Key1": "value1"}
It means that your response from server is string, so you must need to parse it as JSON:
msg = JSON.parse(msg);
alert(msg);
// [object Object]
Now, the other part of your code is correct:
$.each(msg,function(key, val) {
$('<option />', {value: key, text: val}).appendTo("#sampleResp");
});
So your code looks like this:
$(function() {
$.ajax({
type : "GET",
url : "countries/getname",
contentType : "application/json; charset=utf-8",
dataType : "json",
success : function(msg) {
msg = JSON.parse(msg);
$.each(msg,function(key, val) {
$('<option />', {value: key, text: val}).appendTo("#sampleResp");
});
}
});
});
You are passing an array of objects in the message.
Why don't you just send a map instead that is the values are just within { key1:"value1", key2:"value2"}.
With this you can just access the values like this
$.each( msg, function(k, v)
{
alert( "Key: " + k + ", Value: " + v );
});

Categories

Resources