jquery binding a key value pair - javascript

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

Related

How to use pass ajax data that is displaying in html?

I have a question, that I can't seem to find the 'best' solution for my question.. I have an AJAX call that displays data in the DOM, via jQuery.
JSON
[{
"id":"123"
},
{ "id":"456"
}]
JS
$(document).ready(function() {
$.ajax({
url: 'get/data',
dataType: 'json',
data: '{}',
success: function(data) {
var html = '';
$.each(data, function(i) {
html += '<p>My ID: ' + data[i].id + '</p>';
}
$('#id').append(html);
},
error: function(err) {
console.log(err);
}
})
});
As you can see I am displaying that data here. I would like to pass that ID to another AJAX call by selecting a checkbox and pushing a button or perhaps clicking a link. Whats the best way to accomplish this?
EDIT: I apologize, my actual issue is related to array data. I have updated the code. I am displaying an JSON array in the html now, and I want to pass the id of the user/row that I click?
Thanks,
Andy
$(document).ready(function() {
var resid;
$.ajax({
url: 'get/data',
dataType: 'json',
data: '{}',
success: function(data) {
resid = data.id;
var html = '';
html += '<p>My ID: ' + data.id + '</p>'; $('#id').append(html);
},
error: function(err){
console.log(err);
}
});
$('link').click(function () {
// pass id to second ajax
});
});
try jquery-template
https://github.com/codepb/jquery-template
hope help you

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

Trying to populate Select with JSON data using JQUERY

It looks like everything has gone fine retrieving the data from the ajax call, but I having trouble to fill the select with the JSON content, it keeps firing this error in the console:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
The JS is this
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var $select = $('#newStatus');
$.each(response,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
The JSON looks like this:
[{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
I think you need something like this.
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var json = $.parseJSON(response);
var $select = $('#newStatus');
$.each(json ,function(index, object)
{
$select.append('<option value=' + object.s_id+ '>' + object.s_name+ '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to parse the response to Json.
Then you could use the $.each() function to loop through the data:
var json = $.parseJSON(response);

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

JSON Data is not populated into the Dropdownlist

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

Categories

Resources