Binding dropdown list using ajax and jQuery - javascript

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

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

jQuery AJAX function call

I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>

ajax postback method for refreshing dropdown list

Scoop...
I have a drop down list that might not display a particular option you're looking for. I added a button with pop up modal to type in a field you want to add to the drop down list. It functions perfectly, but I need to add an ajax postback method to refresh the list after the user hits enter. I don't want to refresh the whole page, just the list. any help?
Controller:
public ActionResult AddLeadSource()
{
return View();
}
[HttpPost]
public ActionResult AddLeadSource(string name)
{
LeadSource ls = new LeadSource();
ls.Name = name;
db.LeadSources.Add(ls);
db.SaveChanges();
return Json(new { success = true });
}
JS
<script>
$("#AddNew").change(function () {
var name = $("#Name").val();
// var order = $("#DisplayOrder").val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
url: '/Admin/LeadSource/AddLeadSource',
data: { name: name },
success: function (response) {
//alert("Success " + response.success);
$('#FollowUpNotes').kendoWindow('destroy');
// Refresh the DropDown <-- Heres where I need some help!
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});
In your success function of your Ajax call add this:
$("IdOfDropDownList").data("kendoDropDownList").dataSource.read();
In this way your dropdownlist will call the read function and reload all data. I assumed that your dropdownlist is binding throught read call.
I highly recommend looking at jQuery UI's autocomplete widget. That said,
$('#YourDropDownID option').remove(); //this will remove all option elements inside the <select id="YourDropDownID">
Then you just need to build new ones based on the response data,
for (var o in data) {
if (data[o].Value != undefined) {
$('#YourDropDownID').append('<option value="' + data[o].Value + '">' + ("" + data[o].Display) + '</option>');
}
}
I do this inside the .done() callback of my AJAX:
.done(function (data) {
//above code
}
Depending on the nature of the data you are sending back you may need to loop through it differently. Mine is an array of objects with a Value and Display properties (in my case, account numbers and account names).
//server side controller
var query = #"
Select
SubString([mn_no], 0, 6) As Value,
RTRIM([acct_desc]) As Display
From [some_table]";
return con.Query(query, new { AccountNumber = accounts.Select(x =>
{
return new { Value = x.Value, Display = x.Display };
});

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

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