how do i style my json list to material cards?
My json/javascript:
$(document).ready(function(){
var url="getjson.php";
$.getJSON(url,function(data){
console.log(data);
$.each(data.bananas, function(i,post){
var banana =
"<div>"
+"<h3>"+post.name+"</h3>"
+"<h5>"+post.type+"</h5>"
+"</div>";
$(banana).appendTo("#banana-data");
});
now im trying to display it as a nicelt style list of cards but im struggling:
<div class="row">
<div class="col-md-4">
<div id="banana-data" class="box box-widget widget-user">
<div class="widget-user-header bg-aqua-active">
<h3 class="widget-user-username"></h3>
<h5 class="widget-user-desc"></h5>
</div>
</div>
</div>
</div>
But my content appears outside the style of my
I tried using list as follows:
<ol id="banana-data">
<div class="row">
<div class="col-md-4">
<div class="box box-widget widget-user">
<div class="widget-user-header bg-aqua-active">
<h3 class="widget-user-username"></h3>
<h5 class="widget-user-desc"></h5>
</div>
</div>
</div>
</div>
</ol>
var banana =
"<ol>"
+"<h3>"+post.cname+"</h3>"
+"<h5>"+post.sub_type+"</h5>"
+"</ol>";
$(banana).appendTo("#banana-data");
});
The content displayed inside my style,but the entire list of items in the json file was sitting on the same card,and not separating to create multiple styled cards.
this is my php file that converted the data in the msqli table to json:
<?php
require_once 'dbconfig.php';
$posts = array();
$query = "SELECT * FROM bananas";
$stmt = $db_con->prepare($query);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
$posts['bananas'][] = $row;
}
echo json_encode($posts);
?>
I think you have not append it.You have to use after() method like this..
$("#banana-data").after(banana);
So change your script:
$(document).ready(function(){
var url="getjson.php";
$.getJSON(url,function(data){
console.log(data);
banana = "";
$.each(data.bananas, function(i,post){
banana +=
"<div>"
+"<h3>"+post.name+"</h3>"
+"<h5>"+post.type+"</h5>"
+"</div>";
});
$("#banana-data").after(banana);
Very Good Question:
There are multiple libraries you can use for parsing and styling json:
Handlebars is a library that allows you to parse your json with ease and include each json object in your html
The other one is Moustache.But my solution for you is handlebars.
First turn your json into an actual jsonfile as follows...
$json_data = json_encode($posts);
file_put_contents('ldt.json', $json_data);
Add those two lines in your php instead of your echo.ldt is the filename,you can call it whatever you want.
Nextstep:parse the json file using handlebars..
var yourRequest = new XMLHttpRequest();
yourRequest.open('GET', 'ldt.json');
Then in handlebars on create a function and..instruct handlebars to generate html(myhtml) of parsed json and assign it to an id called:eg mycontainer:
var rawTemplate = document.getElementById("thisTemplate").innerHTML;
var myContainer = document.getElementById("my-container");
my.innerHTML = ourGeneratedHTML;
Then in your html:
<div id="my-container"></div>
<script id="thisTemplate" type="text/x-handlebars-template">
//And here call your objects:Example
{{#each bananas}}
<div class="col-md-4">
<div class="box box-widget widget-user">
<div class="widget-user-header bg-black" style="background: url('{{img}}'>) center center;">
<h3 class="widget-user-username"><b>{{name}}</b></h3>
<h5 class="widget-user-desc">({{type}})</h5>
Just make sure your css actually creates your so called cards etc..and your card list will populate your page exactly as you have styled it with all the objects youve parsed.
Ive simply added small snippets of code.For more information,check out:
Handlebars
Theres nothing wrong with just using ajax and create your own elements,but if you want to kill two birds with one stone,use libraries.
There are also alot of tuts on youtube you can watch.I hope this helps
Related
My end result is supposed to be a list of objects in html. Bootstrap behind this. I'd like for the list to be created dynamically so I don't have to manually create all the divs because I don't know how many there will be. Here's what I have.
I have an array similar to this:
activities =
[
{
"activityOwner": "Raymond Carlson",
"activityDesc": "Complete all the steps from Getting Started wizard"
},
{
"activityOwner": "Flopsy McDoogal",
"activityDesc": "Called interested in March fundraising Sponsorship"
},
{
"activityOwner": "Gary Busy",
"activityDesc": "Get approval for price quote"
}
]
This is the first part where I'm not sure what to do. I can assign the element ids individually for my html like this but what I'd like to do is count how many elements are in my array and create these for me. I won't know how many there are to make these manually. I'm sure there needs to be a loop but I couldn't figure it out.
document.getElementById('activityowner0').innerHTML = activities[0].activityOwner;
document.getElementById('activitydesc0').innerHTML = activities[0].activityDesc;
document.getElementById('activityowner1').innerHTML = activities[1].activityOwner;
document.getElementById('activitydesc1').innerHTML = activities[1].activityDesc;
document.getElementById('activityowner2').innerHTML = activities[2].activityOwner;
document.getElementById('activitydesc2').innerHTML = activities[2].activityDesc;
etc.
etc.
And then...once I have that part, I'd like to know how to create my html divs dynamically based on how many elements are in my array. Again, right now I don't know how many there are so I'm having to create a bunch of these and then have extras if I have too many.
<div class="container">
<div class="row"></div>
<div class="qa-message-list" id="wallmessages">
<br>
<div class="message-item" id="m0">
<div class="message-inner">
<div class="message-head clearfix">
<div class="user-detail">
<h5 class="handle">
<p id='activityowner0'></p>
</h5>
<div class="post-meta"></div>
</div>
</div>
<div class="qa-message-content">
<p id='activitydesc0'></p>
</div>
</div>
</div>
I know this is a big ask so just pointing me in the right direction would be very helpful. I hope my question was clear and I appreciate it.
One way for you to achieve this would be to loop through the objects in your activities array. From there you can use a HTML template to store the base HTML structure which you can clone and update with the values of each object before you append it to the DOM.
In addition, an important thing to note when generating repeated content in a loop: never use id attributes. You will either end up with duplicates, which is invalid as id need to be unique, or you'll end up with ugly code generating incremental/random id at runtime which is unnecessary. Use classes instead.
Here's a working example:
const activities = [{ "activityOwner": "Raymond Carlson", "activityDesc": "Complete all the steps from Getting Started wizard"}, {"activityOwner": "Flopsy McDoogal","activityDesc": "Called interested in March fundraising Sponsorship" }, { "activityOwner": "Gary Busy", "activityDesc": "Get approval for price quote" }]
const html = activities.map(obj => {
let item = document.querySelector('#template').innerHTML;
item = item.replace('{owner}', obj.activityOwner);
item = item.replace('{desc}', obj.activityDesc);
return item;
});
document.querySelector('#list').innerHTML = html.join('');
<div id="list"></div>
<template id="template">
<div class="container">
<div class="row"></div>
<div class="qa-message-list">
<div class="message-item">
<div class="message-inner">
<div class="message-head clearfix">
<div class="user-detail">
<h5 class="handle">
<p class="activityowner">{owner}</p>
</h5>
<div class="post-meta"></div>
</div>
</div>
<div class="qa-message-content">
<p class="activitydesc">{desc}</p>
</div>
</div>
</div>
</div>
</div>
</template>
I have to tweet a quote that I randomly generated using APIs, but my code isn't working. Here is my code, I added comments trying to make it look clearer. I am a novice in coding so it probably has a terrible sintax.
I manage to get my quote by clicking on the "Get another quote" button, but when i want to tweet my quote, clicking on the "Tweet quote" button it wont work and i get the "Uncaught ReferenceError: data is not defined
at pen.js:10" error.
I dont know what i am doing wrong.
(This is a task for FreeCodeCamp). Thanks to everyone who will answer!
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<h2 class="title">Random Quote Generator</h2>
<h4 class="subtitle">A project for the FreeCodeCamp challenge</h4>
<div class="container-box">
<div class="container-quote">
<p class="quote" id ="quote"></p>
<div class="container-author" id="author">
<p></p>
</div> <!--closing div for container author-->
<div class="row">
<div class="col-md-6">
<button id="tweetQuote" href="https://twitter.com/intent/tweet?text=data.quoteText">Tweet this quote!</button>
</div>
<div class="col-md-6">
<button id="newQuote">Get another quote</button>
</div>
</div> <!--row-->
</div> <!--closing div for container quote-->
</div> <!--closing div for container-->
And now the javascript
//setting html elements to variables
var $newQuote = $('#newQuote');
var $quote = $('#quote');
var $tweetQuote = $('#tweetQuote');
//execute function by clicking on button
$newQuote.click(getQuote);
$tweetQuote.click(tweetIt);
var text = data.quoteText;
var author = data.quoteAuthor;
//when getQuote is called call the APIs and get the quote by executing
getQuoteFromAPI
function getQuote() {
$quote.empty();
getQuoteFromAPI();
};
function getQuoteFromAPI() {
var url='https://api.forismatic.com/api/1.0/?
method=getQuote&format=jsonp&lang=en&jsonp=?';
//when the APIs are completely called execute the parseQuote function
$.getJSON(url).done(parseQuote);
//log the datas on the console and transform them into real html elements
function parseQuote (response) {
console.log(response);
document.getElementById('quote').innerHTML = response.quoteText;
document.getElementById('author').innerHTML = response.quoteAuthor;
};
};
function tweetIt() {
var url='https://api.forismatic.com/api/1.0/?
method=getQuote&format=jsonp&lang=en&jsonp=?';
$('#tweetQuote').attr('href', 'https://twitter.com/intent/tweet?text=' + text + '-' + author);
};
I am using a php script to extract values from the database as follows,
<div class="col-md-4" >
<?php
$qry = "SELECT * FROM upperbit_categories";
$rslt = mysqli_query($dbc,$qry);
while ($output = mysqli_fetch_array($rslt)) {
?>
<li class="nav" id="test" style= "text-decoration: none;">
<a href="postad" >
<?php echo $output['Classify'].'<br/>'; } ?>
</a>
</li>
</div>
<div class="col-md-4" id="testing">
</div>
this code gives me below result:
General equipment
Test equipment
Renewable energy
Engineering Services
Trade services
Below is the jQuery bit:
<script>
$(document).ready(function(){
$("#test").click(function(){
var classprod = $(this).text();
$("#testing").text(classprod);
event.preventDefault();
})
});
</script>
However this only outputs line-1 but nothing else i.e. General equipment.
What changes do I have to make to my javascript code in order to be able to display any item clicked?
Little errors, but easy to solve. Your php loop leave a lot of tags opened, an closes just one, then you should use a Class instead on an Id for multiple elements.
Another tip is that you should open and close the ul tag before your list.
HTML
<div class="col-md-4" >
<ul>
<?php
$qry = "SELECT * FROM upperbit_categories";
$rslt = mysqli_query($dbc,$qry);
while($output = mysqli_fetch_array($rslt)){?>
<li class="nav test" style= "text-decoration: none;"><a href="postad" ><?php echo $output['Classify'];?></a></li>
<?php };?>
</ul>
</div>
<div class="col-md-4" id="testing"></div>
JS
<script>
$(document).ready(function(){
$(".test").on('click',function(event){
event.preventDefault();
var classprod = $(this).text();
$("#testing").text(classprod);
})
});
</script>
Also, I don't know what you're doing, but consider to use $(".test a") instead of $(".test")
In General, id of HTML elements should be unique, this requirements can be realized when using jQuery or JavaScript. In your code, you used id="test" for the li element inside a loop, and then you referenced to them using $("#test") then, only first li works due to uniqueness of id.
you can use class instead of id.
I have form partial in Rails, laid out like so:
<div class"row">
<div class="col-md-6" id="top_level">
</div>
</div>
<div class"row">
<div class="col-md-2" id="sub_category1">
</div>
</div>
<div class"row">
<div class="col-md-2" id="sub_category2">
</div>
</div>
<div class"row">
<div class="col-md-2" id="sub_category3">
</div>
</div>
<div class"row">
<div class="col-md-3" id="sub_category4">
</div>
</div>
<div class"row">
<div class="col-md-3" id="sub_category5">
</div>
</div>
It is for selecting categories and sub-categories of items.
listings_controller:
def new
#product_listing = Listing.new
#product_ = Product.find(params[:product_id])
# gon.categories = EbayCategory.all
gon.top_level = EbayCategory.top_level
end
In the model:
scope :top_level, -> { where('category_id = parent_id').order(:id) }
Each category record (17989 of them) has a unique category_id, and a parent_id. As indicated above, the top level category_id = the parent_id for the same record. All the subcategories have their own category_ids, which are the parent_ids of the next level down, and so on, varying between 1 and 5 sub-levels.
I've tried a cascade of view files, which works fine (it renders the correct categories and sub-categories) but I can't pass the listing id that way because I don't know how to transmit 2 ids (one for the parent category, one for the listing id) through the params hash using the link_to url helper, so I lose the id for the listing I'm trying to create while navigating all the sub-categories.
So I'm trying it with jQuery, using the Gon gem. Not only does this mean loading the entire db table (about 7 MB, once I un-comment the line for use in level 2 thru 5) into ram, but I can't figure out how to pass the category_id from the dynamically created top_level list when one of its elements is clicked. There are many levels to go, but right now I'm just trying to console.log the category_id for ONE level, so I can see that it's registering. So far unsuccessful, after trying many different syntaxes and methods, of which this is the latest:
<script type="text/javascript">
$(gon.top_level).each(function(){
$("#top_level").append('<h5>' + this.main_category + " >" + '</h5>').data($(this).category_id);
})
$("#top_level").on('click', 'a', function(){
console.log($(this).data());
});
</script>
...returns
Object {}
to the console.
Any suggestions on how to store ids dynamically with the text category titles?
$('gon.top_level').each(function(){
var lnk = $('<h5>' + this.main_category + " >" + '</h5>')
.find('a').data({'category':$(this).category_id,'anotherKey':'value'});
$("#top_level").append(lnk);
});
$("#top_level").on('click', 'a', function(){
console.log($(this).data('category'));
console.log($(this).data('anotherKey'));
});
To set data use $(elment).data({key:value});
To get data use $(elment).data(key);
I have JSON data that is separated by the day of the week.
If the data was just listed out by just the date's and not in it's own array by day, I'd normally use datatables so that it is filterable. However, I am trying to separate the data so it has headers, like so:
With this json data, I am not sure how I would use data tables to do this and also make it filterable. Does anyone have any suggestions (plugins, etc) that I should use to display the data the way I want in a filterable environment?
This is ultimately how I would like to display the data:
<div id="day_of_week">August 26, 2014</div>
<div id="event">
<span id="time">5:52 AM</span>
<span id="event_name">Page View</span>
<div id="hidden_data">Data: Goes here</div>
</div>
You should use a Templating logic, like #Thimoty suggested, tough implemented manually since you need it to be lightweight. I'm working on a fiddle, I'll post it ASAP.
This is it: http://jsfiddle.net/23e37v18/
HTML
<div id="content">
</div>
<div id="template" style="display: none">
<div class="day_of_week">August 26, 2014</div>
<div class="event">
<span class="time"></span>
<span class="event_name"></span>
<div class="hidden_data"></div>
</div>
</div>
JQuery
var jsonText = '{"August 23, 2014":{"1409069553":{"Data":"Your event"},"1407859953 ":{"Data":"Your event"},"1399911153":{"Data":"Your event"}},"August 24, 2014":{"1409069553":{"Data":"Your event"},"1399911139 ":{"Data":"Your event"},"1399914139":{"Data":"Your event"}},"August 25, 2014":{"1407859953 ":{"Data":"Your event"}}}';
$(document).ready(function(){
var data = JSON.parse(jsonText);
for (var day in data){
$('#content').append(day + '<br/>');
// create block
var blockData = data[day];
var block = $('<div/>').addClass('event_block');
for (var event in blockData){
// your event block
var eventDOM = $('#template .event').clone();
// add content
var date = new Date(event*1000)
// TODO: format date for display
$('.time', eventDOM).append(date);
$('.time', eventDOM).append(blockData[event].Data);
block.append(eventDOM);
}
$('#content').append(block);
}
});