jQuery document ready call sequence - javascript

I have a following problem with jQuery. I use this code:
function populate_select_from_json(select, json_url) {
select.empty();
$.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo(select);
});
});
select.children(":first").attr("selected", true);
}
$(document).ready(function() {
var value_type = $("#value_type");
populate_select_from_json(value_type, SOME_URL);
var unit = $("#unit");
populate_select_from_json(unit, ANOTHER_URL + value_type.val());
});
I wanted to:
Load the document
Get some JSON data from an associated database
Put the data in #value_type <select> item
Get the value of #value_type select, and query the database once again to populate another select item.
The problem is, when I call value_type.val(), it always outputs null, even though the #value_type <select> is correctly populated. What am I doing wrong here?

I suppose something like this may work better with promises.
Along these lines (untested):
var populate_select_from_json = function($select, json_url) {
$select.empty();
return $.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo($select);
});
$select.children(":first").attr("selected", true);
});
};
$(document).ready(function() {
var $value_type = $("#value_type");
var $unit = $("#unit");
populate_select_from_json($value_type, SOME_URL).done(function(){
populate_select_from_json($unit, ANOTHER_URL + $value_type.val());
});
});

Related

JQuery: Populate HTML dropdown menu with JSON

I know this questions been asked before, I've read other posts and couldn't get it to work.
I'm trying to populate a drop down menu with JSON data but I'm having some issues, the drop down appears on my html page but theres nothing in the drop down, not even the "Please Select". Below is my code, do you see any problems with it.
HTML
<select id="dropDown">
</select>
JavaScript
$(document).ready(function () {
$.ajax({
url: 'http://localhost/api/Dynamic?database=',
dataType: 'Json',
success: function (results) {
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
}
});
});
JSON
["Item1","Item2","Item3","Item4"]
Have you included jquery in your html head tag
Please also check your ajax is returning json data
I have make a fiddle and its working fine for me
$(document).ready(function() {
var $el = $("#dropDown");
var results = ["Item1","Item2","Item3","Item4"];
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
});
Here is working jsfiddle
https://jsfiddle.net/o5ju4kja/
var results = ["Item1","Item2","Item3","Item4"];
$(document).ready(function () {
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDown">
</select>
As you can see, the jquery code works. The problem must be in your ajax request not responding the desired json.
The following code snippet is working fine so please verify the following points:
Verify that the request is working and you are receiving the correct answer.
Confirm that jQuery is added - probably it's missing
Verify that there is no error in console
var results = ["Item1","Item2","Item3","Item4"];
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDown">
Is it possible your JSON is not good encoding. Try to add a contentType format in your Ajax request:
$(document).ready(function () {
$.ajax({
url: 'http://localhost/api/Dynamic?database=',
dataType: 'Json',
contentType:"application/json; charset=ISO-8859-1",
cache:false,
success: function (results) {
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
}
});
});

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

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

Jquery UI autocomplete results from JSON file

I am having great difficulty in successfully parsing a JSON file to use within JQuery UI autocomplete
Please see my dev page: http://www.zyredesign.com/autocomplete
The JSON isn't organised as well as I would have hoped as the items keys are ID's eg:
{"140":"Abarth",
"375":"Acura"
}
Etc....
Here is my javascript attempt:
$(document).ready(function() {
$('#cars').autocomplete({
source: function()
{
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
alert( cars_array);
return cars_array;
})
},
minLength: 3,
focus: function( event, ui ) {},
select: function( event, ui ) {
$('#suggestions').html(ui);
return false;
}
});
});
/*
function get_json()
{
var items = new Array();
$.getJSON('json.json', function(data) {
var items = [];
alert( eval ("(" + data + ")") );
// $.each(data, function(key, val) {
//items.push('<li id="' + key + '">' + val + '</li>');
// });
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
return items;
}
*/
Any help would be greatly appreciated, thanks!
The function you've supplied for the source: attribute doesn't return a value. The $.get() function does, but that won't reach the source attribute.
source: function()
{
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
return cars_array;
})
//You need to return something here
}
Also, it may be an issue that you're using an asynchronous call to the json file in a synchronous pattern. In other words, consider this:
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
//Now you definitely have the cars so you can do the autocomplete
$('#cars').autocomplete({
source:cars_array,
minLength: 3,
focus: function( event, ui ) {},
select: function( event, ui ) {
$('#suggestions').html(ui);
return false;
}
});

JSON Results To A Drop down List

Hi I am Working On a Web Form..
I Have A combo Box for holding all The Units.
I Have Taken All The units from the Database Using JSON,now i need to Bind All these Units To the drop down List
How can I Do this...?
function getUnitFamily(pack_detl_ID,select) {
//***********************************//
PageMethods.getUnitFamily(pack_detl_ID,
function(result) {
if (result != null) {
custinfo = eval(result);
if (custinfo != null) {
$('#<%=drpUnit.ClientID%> option').remove();
var objSub = document.getElementById('<%=drpUnit.ClientID%>');
$.each(custinfo, function(i, item) {
listOpt = document.createElement("option");
listOpt.value = item[0];
listOpt.text = item[1];
objSub.add(listOpt);
});
alert(select);
document.getElementById('<%= drpUnit.ClientID %>').value = select;
}
}
}, pageMethodError);
With An example can any one explain
A combobox sounds like you are using an ASP.NET control. Of course, you can bind your items to that control in the code behind. If you are doing some AJAX stuff and have a dropdown ( element>) in your page which you want to populate at client side, you might want to take a look at what jQuery has to offer. For example use the AJAX api to retrieve your data and push that data into your dropdown like so:
var options = $("#options");
$.each(result, function() {
options.append($("<option />").val("sometext").text("sometext"));
});
In the past I have used a plugin when working with dropdowns.
http://www.texotela.co.uk/code/jquery/select
Request the JSON data:
//Get the JSON Data
$.getJSON(url, function(json) {
PopulateDropDownFromJson(json, "#element");
});
and then just pass the JSON into a function that uses the plugin above
function PopulateDropDownFromJson(json, element){
$.each(json, function() {
$(element).addOption(this[valueText], this[displayText], false);
});
}

Categories

Resources