Count elements in ajax/json response - ajax

This is properly pretty simple and has been asked many times before, but it just eludes me, who to do it.
I have 2 dropdowns, where the last one gets populated from the select of the first one. That works, but now I want to preselect for the second dropdown, when there is only one element in the response.
Function:
$( "select[name='r53b']" ).change(function () {
var r53bID = $(this).val();
if(r53bID) {
$.ajax({
url: "/overfladeajax.php",
dataType: 'Json',
data: {'id':r53bID},
success: function(data) {
$('select[name="r53c"]').empty();
$('select[name="r53c"]').append('<option value="">Vælg Lagtykkelse</option>');
$.each(data, function(key, value) {
$('select[name="r53c"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}
});
2 kind of reponses:
{"7":"2 x 100 \u03bcm HS 150 (totalt 200 \u03bcm t\u00f8rfilm)","8":"1 x 40 \u03bcm zink primer + 1 x 120 \u03bcm HS 150 (totalt 160 \u03bcm t\u00f8rfilm)"}
or
{"2":"1 x 80 \u03bcm HS 150"}
How to I make the append, so it will also select the option where only one is available?

You can use Object.keys(yourjson).length to get the length of keys in your json object and then if the count is 1 add selected to that options.
Demo Code :
var data = {
"2":"1 x 80 \u03bcm HS 150"
}
var count = Object.keys(data).length//get key length
console.log("length is "+count)
$('select[name="r53c"]').append('<option value="">Vælg Lagtykkelse</option>');
$.each(data, function(key, value) {
//if length is 1
if (count == 1) {
$('select[name="r53c"]').append('<option selected value="' + key + '">' + value + '</option>');
} else {
$('select[name="r53c"]').append('<option value="' + key + '">' + value + '</option>');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="r53c">
</select>

Related

AJAX dropdown list down not update with var string variable

I have a test script to update a county drop down list whenever the year or state is updated. When I used a literal string when year is selected, the county list updated fine. However when I tried to the county list using an ajax call and used a (var options) to build the list, the drop down list value changed to an empty list even though I verified the value of (var options) contains valid drop down list options.
Please help!
Thanks,
$('#State').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year:year
};
alert("State changed:" + state + ":" + year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
$('#DataId').html("<option value='Select'>Select-S</option><option value='16'>Alameda-S</option>");
alert("Statitical Areas(S): " + options);
//$('#DataId').html(options); //This should work. How to get the value of options into the string
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
$('#Year').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year: year
};
alert("Year changed:" + state +":"+ year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
//$('#DataId').html("<option value='Select'>Select-Y</option><option value='16'>Alameda-Y</option>");
$('#DataId').html(options); //This should work. How to get the value of options into the string
alert("Statitical Areas(Y): " + options);
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
});
function AjaxCall(url, data, type) {
  return  $.ajax({
     url:  url,
     type:  type  ?  type  :  'GET',
     data:  data,
     contentType:  'application/json'
   });
}  
Instead of using another function to call your $.ajax why not call it immediately. There’s no performance improvement on what you had done. Try to revert your code and just add async property if you want to wait the response before proceeding to your lower conditions.
I hope this will help you

Ajax call after 10 second automatic inside a loop

jQuery:
// Load message
(function loadAdmin() {
$.ajax({
type: 'POST',
data: 'c_id=' + $(this).data('c_id') + '&offset=' + $(this).data('offset'), //'foo='+ bar+'&calibri='+ nolibri,
dataType: 'json',
url: $("#webroot").text() + 'chats/loadMsg',
success: function (data) {
var id = 0;
$.each(data, function (i, item) {
if (item.Chat.status == 'active') {
$('.temp_msg').remove();
}
if (!$('#' + item.Chat.id)[0]) {
if (item.Chat.admin_message) {
$('<div class="msg_a" id="' + item.Chat.id + '">' + item.Chat.admin_message + '</div>').insertBefore('.' + $(this).data('c_id') + ' .msg_push');
}
if (item.Chat.client_message) {
$('<div class="msg_b" id="' + item.Chat.id + '">' + item.Chat.client_message + '</div>').insertBefore('.' + $(this).data('c_id') + ' .msg_push');
}
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
id = item.Chat.id;
});
$('.' + c_id + ' .msg_head').data('offset', id)
},
complete: function () {
// Schedule the next request when the current one's complete
setTimeout(loadAdmin, 10000);
}
});
})();
// END load message
I set c_id statically.This works fine. But I want to do this same action for all activated class.
This is something like this:
$('.activated').each(function () {
// do ajax call
loadAdmin();
});
Here crucial situation is for first iteration there start a recursion of loadAdmin(); function calling, then again start first iteration and never step up to second iteration. How can I meet my situation. Thanks
you can use setInterval() function for complete your requirements.
Like this :
$('.activated').each(function () {
// do ajax call
setInterval(loadAdmin(), 10000); // This will call this function in every 10 sec
});
Try this. I hope you will found it.

jquery AJAX pulls data from XML - last 4 items only

I am working on a sort of aggregator/tweet wall. At the mo it only uses data from an XML file (of our latest news). I made a bit of a mistake in the logic, though.
At present it only pulls items from the last 30 days. Live demo takes a few secs to load (using last 240 days for extra content to work with). However, I need it to:
Pull the last 4 items in chrono order.
Shuffle that array so they are
random ordered (but will all be "fresh" news).
Output that array.
jQuery(function () {
$.ajax({
url: 'http://www.sagittarius-digital.com/news.rss',
dataType: 'xml',
complete: function() {
/*Init masonry.js*/
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
// options
gutter: 20,
columnWidth: 320,
itemSelector: '.item'
});
}
}).done(function (xml) {
var items = [];
$(xml).find('item').each(function () {
var $item = $(this);
var date = new Date($item.find('pubDate').text());
var date_30 = new Date().getTime() - (1000*60*60*24*240); /* last figure = number of days to sort back from */
var yyyymmdd = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate();
if ( date_30 < date.getTime() ) { // newer than 30 days
var array = '<div class="item"><h2>News</h2>';
array += '<p>' + yyyymmdd + '</p>';
array += '<a href="' + $item.find('link').text() + '">';
array += '<h2>' + $item.find('title').text() + '</h2>';
array += '<p>' + $item.find('description').text() + '</p>';>
array += '<p>Category: ' + $item.find('category').text() + '</p>';
array += '</a>';
array += '</div>';
items.push(array);
}
});
$('div.item').after(items.join(' '));
}).fail(function () {
console.log('error', arguments)
});
});
Basically after that I need to add a second RSS feed with different info doing the same, a Twitter ajax call and facebook ajax call. So I will have 12 bits of data that are all the 4 "freshest", these will then shuffle into a random order and output, so there is a nice even mix.

JQuery Select Populate

i have to items on my html
a Input text (company) field and a select (Company_List)
when user types in the text field i want jQuery to use /Home/SearchSynonym/ to get the names and display it in select (the SearchSynonym takes the value user types and do a wildcard search and returns ID and NAME )
can some one help , am new ti jQuery
Leb
You need to clarify as to in which format does SearchSynonym return the IDs and NAMEs? Is it in JSON? If it is in JSON, then try the following:
var companyList = $("#Company_List");
$("#company").change( function(){
$.getJSON("/Home/SearchSynonym/",{ query: $(this).val() }, function(response){
var responseList = "";
$.each(result, function(index, item){
responseList += "<option value='" + item.id + "'>" + item.name + "</option>";
});
companyList.html(responseList);
});
});
This would work if your 'company' text field bears the id="company" in the tag decleration, your 'Company_List' dropdown bears the id="Company_List" in the tag decleration and your server end receives the parameter "query" for pulling records.
You can use setTimeout. Try this:
var companyList = $("#Company_List");
$("#company").change( function(){
setTimeout( function() {
$.getJSON("/Home/SearchSynonym/",{ query: $(this).val() }, function(response){
var responseList = "";
$.each(result, function(index, item){
responseList += "<option value='" + item.id + "'>" + item.name + "</option>";
});
companyList.html(responseList);
});
}, 2000);
});
The value of 2000 indicates a 2 second delay.

Insert json data into text input

I have a function that adds a new patient to the database, gets the json data back and then adds the new patient to the select menu. That works fine. I need to add that data into the corresponding text inputs i.e., input#patient_id, input#patient_firstname, etc. which should occur in the .ajax complete, but nothing happens.
Would appreciate any help!!
Ajax
$('#newpatient').click(function() {
var patientadd = $('#patientaddform').serializeArray();
$.ajax({
url: 'adam.php',
type: "POST",
data: patientadd,
dataType: 'json',
success: function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option selected="selected" value="' + data[i].patient_id + '">' + data[i].patient_firstname + ' ' + data[i].patient_lastname + ' : ' + data[i].patient_dob + '</option>';
}
alert(html);
$('#patientselect').prepend(html);
$('#patientselect').selectmenu('refresh', true);
},
complete: function (data) {
for(var id in data) {
$('input#' + id).val( data[id] );
}
}
});
});
json data returned
[{"patient_id":"22","patient_firstname":"","patient_lastname":"","patient_dob":"0000-00-00"}]
the corresponding text input fields are input#patient_id, input#patient_firstname, etc, that is why I'm trying to add the 'input#' to the id in the ajax complete and then add that val to the text input.
The params for the complete call back are jqXHR and textStatus. Not data. See http://api.jquery.com/jQuery.ajax/ for the correct definition of complete(jqXHR, textStatus)
Your json data is an array of objects, so you have to add take the first element of the array like this:
for(var id in data[0]) {
$('input#' + id).val( data[0][id] );
}
Or you have to adapt the server response.
Also consider #techfoobar's answer:
The params for the complete call back are jqXHR and textStatus. Not data. See http://api.jquery.com/jQuery.ajax/ for the correct definition of complete(jqXHR, textStatus)

Resources