Loop through JSON and populate data dynamically - javascript

I'm trying to iterate through JSON data and populate the content dynamically using jQuery.
First I do an Ajax request
Then I loop through the data and create the HTML tags dynamically
I create a div container with a class of "product-wrapper" for each JSON object (in this case 2 divs product-wrapper). As you can see on the example of my JSON data, each object has an array of objects "details".
From my second foreach loop - how can I populate the data of "details" within its appropriate "product-wrapper" div?
JavaScript
myApp.init = function(){
var rates = {
products: $('.products-container'),
init: function(){
rates.showRates();
},
showRates: function(){
$.each(utils.rates, function(index, value){
rates.products.append(
'<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div class="product-details"></div>' +
'</div>'
);
$.each(value.details, function(i,val){
$('.product-details').append('<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>');
});
});
}
};
var utils = {
rates: '',
url: $('.business-interest-rates').attr('data-rates-json'),
init: function(){
utils.ajaxRequest();
},
ajaxRequest: function(){
$.ajax({
url: utils.url,
dataType: 'json',
success:function(data){
utils.rates = data;
if($('#interest-rates').length > 0){
rates.init();
}
},
error: function(e){
console.log(e.message);
}
});
}
};
utils.init();
};
JSON
[
{
"name":"Australian dollar (AUD)",
"currency":"AUD",
"details":[
{
"balance": "1+",
"grossRate": "1.700",
"aer": "0.5"
},
{
"balance": "500,000+",
"grossRate": "2.100",
"aer": "2.00"
},
{
"balance": "1,500,000+",
"grossRate": "2.450",
"aer": "1.00"
}
]
},
{
"name":"EURO (EU)",
"currency":"EU",
"details":[
{
"balance": "1+",
"grossRate": "1.700",
"aer": "1.50"
},
{
"balance": "500,000+",
"grossRate": "2.100",
"aer": "2.20"
}
]
}
]

Either don't use a CSS class to append your stuff but unique ids, or first generate the whole HTML code (wrapper and details all together) in one step and then append it.
// use unique IDs for appending
function () {
$.each(utils.rates, function (index, value) {
rates.products.append(
'<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div id="product-details-' + value.name + '"></div>' +
'</div>'
);
$.each(value.details, function (i, val) {
$('#product-details-' + value.name).append('<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>');
});
});
}
// first generate all html code, then append
function () {
$.each(utils.rates, function (index, value) {
var html = '<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div class="product-details">';
$.each(value.details, function (i, val) {
html += '<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>';
});
html += '</div>' +
'</div>';
rates.products.append(
html
);
});
}

Related

How do i alert users when they not able to access the server

var serviceURL = "http://mywebsite.com/mobile/";
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
function getEmployeeList() {
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="reportlist.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
My problem with my script is that any time i try to reach server and it is down i want my application to be alert people that the server is down for now
var serviceURL = "http://mywebsite.com/mobile/";
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
// Use the ajaxError method to handle your error
$(document).ajaxError(function(event, request, settings) {
//Then you can use the .hide() to hide div alert users for error
$('#errorserver').hide();
alert("Error accessing the server");
});
function getEmployeeList() {
//Then you can use the .show() to show loading
$('#errorserver').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
//Then you can use the .hide()
$('#errorserver').hide();
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="reportlist.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
//Add this div to your html page
<div id="errorserver"/><img src="image/loading.png" alt="Loading please wait.."></div>
You have to handle errors using .fail method:
$.getJSON(serviceURL + 'getemployees.php', function(data) {
// ... your implementation
}).fail(function (err) {
// ... this callback will be invoked
// ... in case any error of the server
});

Switching divs via JS (ASP.NET MVC)

I have AJAX request to get Question1-Question10 from back-end
Here is code of request
<script>
$(document).ready(function() {
question_block();
});
function question_block() {
$.ajax({
url: '#Url.Action("QuestionBlocks", "Interwier")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function(result) {
var email = result;
for (var i = 0; i <= email.length - 1; i++) {
var question = '<div style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question1 + '</div>'+
'<div style="font-size:20px;">' + email[i].Question2 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question3 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question4 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question5 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question6 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question7 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question8 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question9 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question10 + '</div>';
$("#questions").append(question);
}
},
error: function() {
alert("Smth wrong in controller");
}
});
}
I need to make visible first div for default and when I click button, for example next I need to hide first div and make visible second, etc.
How I can do this?
<script>
$(document).ready(function() {
question_block();
});
function question_block() {
$.ajax({
url: '#Url.Action("QuestionBlocks", "Interwier")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function(result) {
var email = result;
for (var i = 0; i <= email.length - 1; i++) {
var question = '<div style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question1 + '</div>'+
'<div style="font-size:20px;">' + email[i].Question2 + '</div>' +
'<div style="font-size:20px;" class="que show'">' + email[i].Question3 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question4 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question5 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question6 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question7 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question8 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question9 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question10 + '</div>';
$("#questions").append(question);
}
},
error: function() {
alert("Smth wrong in controller");
}
});
}
// click on next
function next(){
$(".que").each(function(){
if( $( this ).hasClass('show') ){
$( this ).removeClass("show").addClass('hide');
$( this ).next().removeClass("hide").addClass('show');
}
});
}
// same you can do for back button
use two classes "activeQue" and "hiddenQue"
by default give first question activeQue class and give hiddenQue to rest.
then you can use code like on next button to show hide questions
var element = $(".activeQue");
$(element).removeClass("activeQue").addClass("hiddenQue");
$(element).next().addClass("activeQue");
something like this
you can do this with set the second div take style="display:none" by default
and when you click you will hide fist div and show second div jquery code :
$("#first").slideUp();
$("#second").slideDown();

Ajax JSON data and lightbox conflicts

I have a gallery setup with the lightbox plugin lightGallery
The gallery works perfect with static HTML. The problem arises when I dynamically grab API data and try to have the lightbox working on those items.
I can't seem to get another lightbox to both work with this function and load an HTML block from the page correctly (load the one that's been dynamically generated). This app does the correct HTML grabs, if I can get the conflict resolved.
Any initial thoughts? Anyone else run into anything similar?
JS:
//----------------------------------------------------------------//
//---------------// Calling Lightgallery //---------------//
//----------------------------------------------------------------//
$('#photoBox').lightGallery({
selector: '.tile',
download: false,
counter: false,
zoom: false,
thumbnail: false,
mode: 'lg-fade'
});
// ----------------------------------------------------------------//
// ---------------// Unsplash Photos //---------------//
// ----------------------------------------------------------------//
// Filter Difference based on button click
$('button').click(function () {
$('button').removeClass("active");
$(this).addClass("active");
var unsplashAPI = "#URL";
var order = $(this).text();
var sortOptions = {
order_by: order,
format: "json"
};
function displayPhotos(data) {
var photoData = '';
$.each(data, function (i, photo) {
photoData += '<a class="tile" data-src="' + photo.urls.regular + '">' + '<img alt class="photo" src="' + photo.urls.regular + '">' + '<div class="caption-box" id="' + photo.id + '">' + '<h1 class="photo-title">' + 'Photo By: ' + photo.user.name + '</h1>' + '<p class="photo-description"> Description: Awesome photo by ' + photo.user.name + ' aka: ' + photo.user.username + ' So far this photo has ' + '<span>' + photo.likes + '</span>' + ' Likes' + '</p>' + '</div>' + '</a>';
});
$('#photoBox').html(photoData);
}
$.getJSON(unsplashAPI, sortOptions, displayPhotos);
}); // End button
HTML:
<div class="content" id="photoBox"></div>
-- Thanks
Call the plugin after the data is appended to the page
function displayPhotos(data) {
var photoData = '';
$.each(data, function (i, photo) {
photoData += '<a class="tile" data-src="' + photo.urls.regular + '">' + '<img alt class="photo" src="' + photo.urls.regular + '">' + '<div class="caption-box" id="' + photo.id + '">' + '<h1 class="photo-title">' + 'Photo By: ' + photo.user.name + '</h1>' + '<p class="photo-description"> Description: Awesome photo by ' + photo.user.name + ' aka: ' + photo.user.username + ' So far this photo has ' + '<span>' + photo.likes + '</span>' + ' Likes' + '</p>' + '</div>' + '</a>';
});
$('#photoBox').html(photoData);
$('#photoBox').lightGallery({
selector: '.tile',
download: false,
counter: false,
zoom: false,
thumbnail: false,
mode: 'lg-fade'
});
}

bootstrap collapsible not collapsing after expanded

Collapsible did not collapse after being expanded. It is dynamically created in popover.
Here is my jsFiddle:
$('.tooltiphelp').tooltip();
$('[data-toggle="tooltip"]').tooltip();
$('[data-toggle="popover"]').popover();
$('[data-toggle="collapse"]').collapse();
jQuery('document').ready(function() {
jQuery('#accordionRank').on('show hide', function() {
jQuery(this).css('height', 'auto');
});
jQuery('#accordionRank').collapse({ parent: true, toggle: true });
});
var popover = $("#noteListDiv").find('.positive').popover({
trigger: 'click',
placement: 'bottom',
content: function () {
return func_getRank($(this).closest('tr').prop('id'));
}
});
var func_getRank = function (ID) {
var Rankdata = {"Rank":[{"ID": "114077", "NL": "1 of 25", "OF": "1 of 30", "MLB": "1 of 240"}]};
var cshtml;
cshtml = '<div>'
+ '<div class="accordion" id="accordionRank">'
+ '<div class="accordion-group">'
+ '<div class="accordion-heading">'
+ '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordionRank" href="#collapseNL">'
+ 'NL Rank: ' + Rankdata.Rank[0].NL
+ '</a>'
+ '</div>'
+ '<div id="collapseNL" class="accordion-body collapse">'
+ '<div class="accordion-inner">'
+ 'Anim pariatur cliche...'
+ '</div>'
+ '</div>'
+ '</div>'
+ '<div class="accordion-group">'
+ '<div class="accordion-heading">'
+ '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordionRank" href="#collapseOF">'
+ 'OF Rank: ' + Rankdata.Rank[0].OF
+ '</a>'
+ '</div>'
+ '<div id="collapseOF" class="accordion-body collapse">'
+ '<div class="accordion-inner">'
+ 'Anim pariatur cliche...'
+ '</div>'
+ '</div>'
+ '</div>'
+ '<div class="accordion-group">'
+ '<div class="accordion-heading">'
+ '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordionRank" href="#collapseMLB">'
+ 'MLB Rank: ' + Rankdata.Rank[0].MLB
+ '</a>'
+ '</div>'
+ '<div id="collapseMLB" class="accordion-body collapse">'
+ '<div class="accordion-inner">'
+ '<table id="MiniLeaderboard">'
+ '<thead><tr>'
+ '<th>Rank</th>'
+ '<th>Hitter</th>'
+ '<th>BAVG</th>'
+ '<th>Hits/AB</th>'
+ '</tr></thead>'
+ '<tbody><tr>'
+ '<td>1</td>'
+ '<td>Christian Yelich</td>'
+ '<td>.470</td>'
+ '<td>39-for-83</td>'
+ '</tr>'
+ '<tr>'
+ '<td>2</td>'
+ '<td>Ryan Braun</td>'
+ '<td>.397</td>'
+ '<td>27-for-68</td>'
+ '</tr>'
+ '<tr>'
+ '<td>3</td>'
+ '<td>Adam Eaton</td>'
+ '<td>.370</td>'
+ '<td>37-for-100</td>'
+ '</tr>'
+ '<tr>'
+ '<td>4</td>'
+ '<td>Joey Votto</td>'
+ '<td>.369</td>'
+ '<td>31-for-84</td>'
+ '</tr>'
+ '<tr>'
+ '<td>5</td>'
+ '<td>Edwin Encarnation</td>'
+ '<td>.364</td>'
+ '<td>28-for-77</td>'
+ '</tr></tbody>'
+ '</table>'
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>'
;
return $(cshtml).html();
};
Data text should come from JSON.
Here is the issue, please watch this screen cast.
Please help! Thanks in forward for your help.
I've updated my jsFiddle and it's now working. Maybe not a good idea but looks good for now.
$(document).on('click', '.accordion-toggle', function(e) {
$(e.target).css('text-decoration','none');
var $_this = $(e.target).parent().next("div");
var $_inner = $_this.find('div:first-child');
if($_inner.hasClass('in')){
$_inner.removeClass("in");
$_this.removeClass("in");
}
else {
$_inner.addClass("in");
$_this.addClass("in");
}
func_accordionToggle(e.target);
});
var func_accordionToggle = function (e) {
var $_this = $(e).parent().parent();
var id = $(e).parent().next("div").attr('id');
switch(id) {
case 'collapseNL':
$('#collapseOF').removeClass("in");
$('#collapseMLB').removeClass("in");
$('#collapseOF').find('div:first-child').removeClass("in");
$('#collapseMLB').find('div:first-child').removeClass("in");
break;
case 'collapseOF':
$('#collapseNL').removeClass("in");
$('#collapseMLB').removeClass("in");
$('#collapseNL').find('div:first-child').removeClass("in");
$('#collapseMLB').find('div:first-child').removeClass("in");
break;
case 'collapseMLB':
$('#collapseNL').removeClass("in");
$('#collapseOF').removeClass("in");
$('#collapseNL').find('div:first-child').removeClass("in");
$('#collapseOF').find('div:first-child').removeClass("in");
break;
};
}
Thanks for all the help Guys.

How to add item into selectize js automatically after document ready?

I have selectize js code. It runs well and shows right option after i type key on select box.
Here is the code :
$('#select-links').selectize({
maxItems: diffItems,
valueField: 'nick_name',
labelField: 'full_name',
searchField: ['nick_name', 'full_name'],
options: [],
create: false,
render: {
item: function(item, escape) {
return '<div id="' + escape(item.id) + '">' +
'<span class="nick_name">' + escape(item.full_name) + '</span>' +
'<span class="full_name"> <' + escape(item.nick_name) + '></span>' +
'</div>';
},
option: function(item, escape) {
return '<div class="box-user clearfix">' +
'<div class="thumb col-xs-1 mr10">' +
'<img class="lazyload" src="'+escape(item.avatar)+'" data-src="' + escape(item.avatar)+'">' +
'</div>' +
'<div class="col-xs-8">' +
'<span class="label" style="color: #000;">' + escape(item.full_name) + '</span>' +
'<span class="caption">/' + escape(item.nick_name) + '</span>' +
'</div>' +
'</div>';
}
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/ajax/origin/search',
type: 'GET',
dataType: 'json',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
}
});
But, i got the problem.
After document ready, i want selectize add item automatically after document / page has already loaded without i have to type the key on select box. How is the code?
#if(isset($_POST['nick']))
$(".chat__list--active").show();
$(".edit").hide();
$('.chat__list').hide();
$('#cancel-participants').show();
if(diffItems != 49) {
$('#save-participants').show();
}
alert("{{$_POST['nick']}}");
// This is the code's place to add item automatically and the key is $_POST['nick']
#endif
Thank you.
Sorry for bad english
You can add options to existing selectize by following approach:
$(document).ready(function(){
var selectize_element = $("#select-links")[0].selectize;
selectize_element.addOption({
text:'First Item',
value: 'First Item'
});
selectize_element.refreshOptions() ;
selectize_element.addItem('First Item');
});

Categories

Resources