Using jquery append() puts the appended content outside of the appended background - javascript

I'm using the append function to add different divs, images, links and text onto my html. When I do this though, the content that I get from a JSON file that I'm trying to append is being placed outside of the background that I want it to be placed on. Here is what the content is supposed to look like:
http://i.stack.imgur.com/iShVe.png
The image and text is placed onto the gray background when I create this html content myself, but when I try to create all this content with append(), it puts all the content to the left of the background:
Here is also the codepen that I'm doing it on if you needed to see that: http://codepen.io/JaGr/pen/XXMPQY
html:
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Droid+Serif' rel='stylesheet' type='text/css'>
<div>
<div class="header">
<div>
Camper
</div>
<div>
News
</div>
</div>
<div class="stories">
<div class="story">
<img src="http://a5.mzstatic.com/us/r30/Purple5/v4/5a/2e/e9/5a2ee9b3-8f0e-4f8b-4043-dd3e3ea29766/icon128-2x.png" class="profilePicture">
<div class="headline">Test Headline</div>
<div class="author">by - TestName</div>
<div class="likes"><img src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-heart-128.png" class="heartIcon"> 13</div>
</div>
</div>
</div>
css:
body {
background-image: url("http://s22.postimg.org/bondz7241/grey_wash_wall.png")
}
.header {
font-family: 'Oswald', sans-serif;
font-size: 100px;
float: left;
color: #A9A9A9;
border-right-style: solid;
border-bottom-style: solid;
margin-left: 20px;
margin-top: 10px;
padding-right: 135px;
padding-bottom: 18px;
width: 210px;
margin-bottom: 29px;
}
.story {
text-align: center;
float: right;
background-color: #A9A9A9;
width: 230px;
height: 330px;
margin-bottom: 30px;
margin-right: 30px;
box-shadow: 2px 2px 13px;
}
.headline, .author, .likes {
padding-top: 7px;
font-family: 'Droid Serif', serif;
}
.likes {
vertical-align:middle
padding-top: 5px;
}
a {
text-decoration: none;
color: #0052cc;
}
.profilePicture {
width: 230px;
height: 230px;
}
.heartIcon {
width: 15px;
height: 15px;
}
javascript:
$(document).ready(function() {
$.getJSON("http://www.freecodecamp.com/news/hot", function(json) {
for (var x = 0; x < json.length; x++) {
var headline = json[x].headline;
var headlineLink = json[x].link;
var authorName = json[x].author.username;
var authorNameLink = "http://www.freecodecamp.com/" + authorName;
var authorPicture = json[x].author.picture;
var likes = json[x].rank;
if (headline.length > 15) {
headline = headline.slice(0, 16);
}
var divStory = '<div class="story">'
var profilePic = '<img src="' + authorPicture + '"' + ' class="profilePicture">'
var divHeadline = '<div class="headline">' + headline + '</div>'
var divAuthor = '<div class="author">by - ' + authorName + '</div>'
var divLikes = '<div class="likes"><img src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-heart-128.png" class="heartIcon">' + likes + '</div>'
var lastDiv = '</div>'
$(".stories").append(divStory, profilePic, divHeadline, divAuthor, divLikes, lastDiv)
}
});
});
I think my html and css is OK, it works alright when I type in the code myself; it's just the javascript that introduces the problem. I've checked the variables and incoming JSON and they both seem fine as well, so I think the problem is just with append() itself, but I don't know exactly whats causing it.

It is the jquery append multiple elements.
$(".stories").append(divStory, profilePic, divHeadline, divAuthor, divLikes, lastDiv)
I haven't found out exactly why it created the issue, but change it to will fix the problem.
$(".stories").append(divStory + profilePic + divHeadline + divAuthor + divLikes + lastDiv)
Check fix here

Did u ever use the devtools? (F12)
They're pretty useful, and you can see on first sight that your elements aren't wrapped into the .story-tags.
I'd do it like this:
var tplStory = '\
<div class="story">\
<img src="{{authorPicture}}" class="profilePicture">\
<div class="headline">{{headline}}</div>\
<div class="author">by - {{authorName}}</div>\
<div class="likes"><img src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-heart-128.png" class="heartIcon">{{likes}}</div>\
</div>';
$(".stories").append(
divStory
.replace('{{authorPicture}}', authorPicture)
.replace(...)
)

Related

Clone div based on content of span

There are random number of div's as show below, I am trying to clone these div on click. when cloning I want to change the content to actual content + no of clones it has (based on content of span , not the id or classes of "clone-this")
eg.
If I click the first "chrome" div, since the body already have "chrome (1) and chrome (2)" , div with content "chrome (3)" Should appear .
If I click the 2nd div ie. "Mozilla Firefox", since there is no cloned version, a div with content "Mozilla Firefox (1)" should appear.
and so on.
I tried to make this, but when i clone the count is based on class , not the content . so clicking on "chrome" div will clone "chrome (5)" not "chrome (3)" .
Also in my implementation when i click the "chrome (1)" div, it will clone as "chrome (1)(5)" . I want this to be like "chrome (3)"
how can i achieve this?
note that there will be any number of divs at first. 5 is just for and example.
jsfiddle here
$(document).on('click', '.clone-this', function(){
var CloneContainer = $(this).clone();
var no = $('.clone-this').size();
CloneContainer.html(CloneContainer.html() + " (" + no + ")");
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>
To accomplish that, you should check "content" of each item and count the number of elements which have same text. But, there is one problem here; each element (for example Chrome, Chrome (1), Chrome (2)) has different content. So, you may split the text using parenthesis or you may use RegEx (recommended).
$(document).on('click', '.clone-this', function(){
var CloneContainer = $(this).clone();
var content = CloneContainer.find('span').html().split(' (')[0];
var no = $(".clone-this:contains('"+content+"')").size();
CloneContainer.html( CloneContainer.html() .split(' (')[0] + " (" + no + ")" );
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>
On the snippet above, you may see basic version of it. But you MUST consider the "similar content" issue like following.
Chrome
Chrome Mobile
Firefox
Firefox Mobile
Here is another way to get you going. I "trim" the clicked div to its base name and then loop through the divs and get the length of all which contain the same base name.
After that I modify the cloned element to fill in the right count of the cloned element appropriately:
var regExp = /\([0-9]+\)/;
$('.clone-this').click(function(e){
var target = e.target.textContent;
var matches = regExp.exec(target);
var elements = $('.clone-this');
var count = elements.length;
var index = 0;
if (null != matches) {
target = matches.input.substr(0, matches.input.lastIndexOf(" "));
}
for(var i = 0; i < count; i++){
index += (elements[i].textContent.indexOf(target) > -1) ? 1: 0;
}
var CloneContainer = $(this).clone();
CloneContainer.html(CloneContainer.html().split('(')[0] + "(" + index + ")" );
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>

Creating and showing div's with javascript

I am trying to create a list of friends and to do this I will need to create a div for each one. The code I tried hasn't worked.
Relevant JavaScript (Now at bottom of page):
document.getElementById("name").innerHTML = user;
document.getElementById("profilePic").src = "users/" + user + "/profilePic.jpg";
var friends = ["Test"];
var friendArea = document.getElementById("friendsDiv");
for (i=0; i < friends.length; i++) {
var friendDiv = document.createElement("div");
friendDiv.setAttribute("class", "friend");
var friendImage = document.createElement("img");
friendImage.setAttribute("class", "friendImage");
friendImage.setAttribute("src", "users/" + friends[i] + "/profilePic.jpg");
friendDiv.appendChild(friendImage);
friendArea.appendChild(friendDiv);
}
Relevant CSS:
.friends {
width: 100%;
height: 90%;
overflow-x: hidden;
overflow-y: auto;
}
.tools {
width: 100%;
height: 10%;
box-shadow: 0px 0px 3px 1px #898989;
}
.friend {
width: 100%;
height: 20%;
padding: 1%;
}
.friendImage {
height: 80%;
width: auto;
border: medium #CCCCCC solid;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
}
The HTML isn't really important but I'll include it anyway.
<div class="window">
<div class="rightCorner">
<img src="images/pPicTemp.png" id="profilePic">
</div>
<div class="holder" id="profileData">
<span id="name"></span>
</div>
<div class="sideBar">
<div class="friends" id="friendsDiv">
</div>
<div class="tools">
</div>
</div>
Is your script in a tag? Also is the document loaded when you attempt this? What does the console says? Is it working with no css? Also if photo path doesnt work there is no other content in the div did you try outputting something else?
You're not appending the friendImage to the friendDiv.
It should look like this:
var friends = ["Test"];
var friendArea = document.getElementById("friends");
for (i=0; i < friends.length; i++) {
var friendDiv = document.createElement("div");
friendDiv.setAttribute("class", "friend");
var friendImage = document.createElement("img");
friendImage.setAttribute("class", "friendImage");
friendImage.setAttribute("src", "users/" + friends[i] + "/profilePic.jpg");
friendDiv.appendChild(friendImage);
friendArea.appendChild(friendDiv);
}
Also, be sure to put this script at the bottom of your HTML <body></body> tag so that the HTML has loaded the entire document before the JavaScript attempts to get elements from the page.

Javascript isn't correctly adding and subtracting floats

I've been messing about with an inventory-like system for a website I'm working on.
I don't usually use JavaScript, So this little problem has been driving me crazy.
I'm trying to add two floats together using two different functions.
One is addition, One is subtraction.
This is the code:
function addItem(item){
$("#item-" + item.toString()).insertAfter("#selected h1");
$("#item-" + item.toString() + " a").attr("onclick","remItem(" + item.toString() + ")");
updateTotal(item, 0);
}
function remItem(item){
$("#item-" + item.toString()).insertAfter("#my h1");
$("#item-" + item.toString() + " a").attr("onclick","addItem(" + item.toString() + ")");
updateTotal(item, 1);
}
function updateTotal(item, action){
if(action=0){
var value = $("#item-" + item.toString() + " a .value").text().replace("$ ", "");
var oldVal = $(".total").text().replace("$ ", "");
var newVal = parseFloat(value) + parseFloat(oldVal);
$(".total").text(newVal);
} else {
var value = $("#item-" + item.toString() + " a .value").text().replace("$ ", "");
var oldVal = $(".total").text().replace("$ ", "");
var newVal = parseFloat(value) - parseFloat(oldVal);
$(".total").text(newVal);
}
}
.wrapper{
text-align: center;
}
.item-holder{
width: 45%;
text-align: left;
padding: 5px;
overflow: auto;
display: inline-block;
background-color: #222;
min-height: 160px;
}
.item-holder h1{
color: white;
margin: 0;
padding: 0;
text-align: center;
}
.smallimg{
margin: 2px 2%;
width: 96%;
}
.item {
margin: 2px 2px 2px 2px !important;
cursor: pointer;
color: #333;
background: rgba(200,200,200,0.9);
text-align: center;
min-width: 60px;
max-width: 100px;
width: 18%;
border: solid medium gray;
display: inline-block;
}
.value{
font-size: 10pt;
font-weight: bold;
padding-top: 5px;
}
.rarity{
font-style: italic;
font-weight: bold;
}
.total{
font-weight: bold;
}
.Consumer{
border-color: rgb(176, 195, 217);
}
.Mil-Spec{
border-color: rgb(75, 105, 255);
}
.Industrial{
border-color: rgb(94, 152, 217);
}
.Restricted{
border-color: rgb(136, 71, 255);
}
.Classified{
border-color: rgb(211, 44, 230);
}
.Covert{
border-color: rgb(235, 75, 75);
}
#selected{
color: white !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<span class="total">$ 0.00</span><br /><br />
<!-- START ITEM HOLDER-->
<div id="my" class="item-holder">
<h1>Your Items</h1>
<div class="item Industrial" id="item-22">
<a onClick="addItem(22);">
<div class="value">$ 0.05</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
<div class="item Restricted" id="item-21">
<a onClick="addItem(21);">
<div class="value">$ 11.40</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
<div class="item Covert" id="item-20">
<a onClick="addItem(20);">
<div class="value">$ 7.65</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
</div>
<!-- END ITEM HOLDER -->
<div id="selected" class="item-holder">
<h1>Selected Items</h1>
</div>
</div>
The first item works fine, You add the item, It updates the total.
Add a second item, It subtracts the new item value from the old one.
Remove the first item and it adds the value to the total.
It's a little messed up, it randomly adds and subtracts.
I'm really not sure why it's causing this, so I came here.
Any ideas what I'm doing what?
Thanks in advance!
CodePen
Inu, in addition to fixing the if(action = 0) bug, you might also like to consider the following :
attach click handlers in javascript, not as HTML attributes.
things will simplify with more carefully chosen jQuery selectors and method chaining.
by delegating click handling to static wrappers (#selected and #my), you can avoid the need to dynamically swap out 'addItem' and 'remItem'. The click action of each item will be automatically determined by the current wrapper.
in the click handlers, this refers to the clicked a element, therefore no need to rediscover it with a jQuery selector, and .closest() will avoid the need to find items by id.
to maintain a reliable total, you should really recalculate from scratch by looping through all items, rather than applying deltas.
by putting values in spans with the '$' outisde, you can get the values directly, without stripping out the symbol.
Put everything together and you should end up with something like this :
HTML
....
<div class="value">$ <span>11.40</span></div>
....
Javascript
$('#my').on('click', '.item a', function(e) {
e.preventDefault();
$(this).closest('.item').insertAfter("#selected h1");
calcTotal();
});
$('#selected').on('click', '.item a', function(e) {
e.preventDefault();
$(this).closest('.item').insertAfter("#my h1");
calcTotal();
});
function calcTotal(item, sign) {
var total = 0;
$("#selected .value span").each(function() {
total += Number($(this).text());
});
$(".total").text(total);
}
untested
You are using the assignment operator = here: if(action=0){ when you should be using the comparisson operator == as if(action==0){

Masonry not working with dynamic content

Masonry is not working with my dynamic content, I don't know why. I don't think it's a bug on my side, at least I've looked at the code for a few hours now and I can't find anything that isn't working.
//reads listbox.php and cycles through the array calling createbox
function listboxs() {
$.ajax({
url: '_php/listbox.php',
success: function (output) {
var jsonArray = $.parseJSON(output);
$.each(jsonArray, function (i, box) {
createbox(box.id, box.name, box.link, box.description, box.tags);
});
}
});
}
//create the code for 1 box
function createbox(id, name, link, description, tags) {
var boxHtml = "",
tagsHtml = "",
descriptionHtml = "";
boxHtml = '' + '<div class="box" id="' + id + '">' + '<div class="boxinfo">' + '<label class="boxname">' + name + '</label>';
$.each(tags, function (i, tag) {
tagsHtml += '<label class="boxtag">' + ((!tag.name) ? tags[i] : tag.name) + '</label>';
});
//if(description.trim().length > 0){
descriptionHtml = '<textarea class="boxdescription" readonly rows="1">' + description + '</textarea>';
//}
boxHtml += tagsHtml + '</div>' + descriptionHtml + '</div>';
$content.html($content.html() + boxHtml);
}
Below is the simplified HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="_css/index.css" />
<link href='http://fonts.googleapis.com/css?family=Marck+Script' rel='stylesheet'
type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Rosario' rel='stylesheet'
type='text/css'>
<script src="_resources/jquery-2.0.3.min.js" type="text/javascript" language="javascript"></script>
<script src="_resources/masonry.pkgd.min.js"></script>
<script type="text/javascript" language="javascript">
$('#content').masonry();
</script>
</head>
<body>
<div id="content" class="js-masonry"></div>
</body>
</html>
I know that I don't need the inline javascript calling masonry on content but it's one of my many tests...
Below is part of the CSS:
#content{
padding: 15px;
min-height: 400px;
}
/*
################################
box
*/
.box{
border: 1px solid black;
float: left;
padding: 5px;
background: #F0F0F0;
margin-left: 5px;
margin-bottom: 5px;
}
.boxinfo{
border-bottom: 1px solid black;
}
.boxname{
font-weight: bold;
}
.boxdescription{
border: none;
outline: none;
background: white;
overflow: hidden;
}
.boxtag{
margin-left: 5px;
}
#boxdecoy{
height: 45px;
}
.boxname, .boxtag, .boxdescription{
font-family: 'Rosario', sans-serif;
font-size: 12px;
}
.boxlink{
text-decoration: none;
color: black;
}
.boxlink:hover{
text-decoration: underline;
}
I'm really going crazy with all of it because I tested creating boxes by hand (this means writting in the html) in content, and if i do masonry works fine. If i create them through the function that you see there it doesn't work... i call listboxs right in the begining of the javascript file after I declare all my vars...
Hope I was clear and you can help me.
You should use appended method. From docs:
Add and lay out newly appended item elements.
Look at this jsfiddle
Try to change your code to
boxHtml += tagsHtml +
'</div>' +
descriptionHtml +
'</div>';
var $boxHtml = $(boxHtml);
$content.append($boxHtml).masonry('appended', $boxHtml);
Adding up to Grin's answer:
You should also apply data-masonry-options='{ "columnWidth": 200, "itemSelector": ".item" }' to your #container.
<div id="content" class="js-masonry" data-masonry-options='{ "columnWidth": 200, "itemSelector": ".item" }'></div>
Like so. It might help with your comment response. I don't have the rep to answer as a comment.

JavaScript $.getJSON Issue

I have a problem with a piece of JavaScript code - a snippet is shown below. Basically the code is issuing a getJSON request to a rails controller and then should process the returned data, building an HTML table and then embedding it in a Div. It doesn't work. I have tried stepping through it with alerts, etc - all to no avail. The data is retrieved from the rails controller and I can verify that. I have placed the piece of code that issues and processes the getJSON request in the niddle of the Rails Welcome page - this is not all mine. The code is below:
<!DOCTYPE html>
<html>
<head>
<title>Ruby on Rails: Welcome aboard</title>
<style type="text/css" media="screen">
body {
margin: 0;
margin-bottom: 25px;
padding: 0;
background-color: #f0f0f0;
font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
font-size: 13px;
color: #333;
}
h1 {
font-size: 28px;
color: #000;
}
a {color: #03c}
a:hover {
background-color: #03c;
color: white;
text-decoration: none;
}
#page {
background-color: #f0f0f0;
width: 750px;
margin: 0;
margin-left: auto;
margin-right: auto;
}
#content {
float: left;
background-color: white;
border: 3px solid #aaa;
border-top: none;
padding: 25px;
width: 500px;
}
#sidebar {
float: right;
width: 175px;
}
#footer {
clear: both;
}
#header, #about, #getting-started {
padding-left: 75px;
padding-right: 30px;
}
#header {
background-image: url("images/rails.png");
background-repeat: no-repeat;
background-position: top left;
height: 64px;
}
#header h1, #header h2 {margin: 0}
#header h2 {
color: #888;
font-weight: normal;
font-size: 16px;
}
#about h3 {
margin: 0;
margin-bottom: 10px;
font-size: 14px;
}
#about-content {
background-color: #ffd;
border: 1px solid #fc0;
margin-left: -55px;
margin-right: -10px;
}
#about-content table {
margin-top: 10px;
margin-bottom: 10px;
font-size: 11px;
border-collapse: collapse;
}
#about-content td {
padding: 10px;
padding-top: 3px;
padding-bottom: 3px;
}
#about-content td.name {color: #555}
#about-content td.value {color: #000}
#about-content ul {
padding: 0;
list-style-type: none;
}
#about-content.failure {
background-color: #fcc;
border: 1px solid #f00;
}
#about-content.failure p {
margin: 0;
padding: 10px;
}
#getting-started {
border-top: 1px solid #ccc;
margin-top: 25px;
padding-top: 15px;
}
#getting-started h1 {
margin: 0;
font-size: 20px;
}
#getting-started h2 {
margin: 0;
font-size: 14px;
font-weight: normal;
color: #333;
margin-bottom: 25px;
}
#getting-started ol {
margin-left: 0;
padding-left: 0;
}
#getting-started li {
font-size: 18px;
color: #888;
margin-bottom: 25px;
}
#getting-started li h2 {
margin: 0;
font-weight: normal;
font-size: 18px;
color: #333;
}
#getting-started li p {
color: #555;
font-size: 13px;
}
#sidebar ul {
margin-left: 0;
padding-left: 0;
}
#sidebar ul h3 {
margin-top: 25px;
font-size: 16px;
padding-bottom: 10px;
border-bottom: 1px solid #ccc;
}
#sidebar li {
list-style-type: none;
}
#sidebar ul.links li {
margin-bottom: 5px;
}
</style>
<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function about() {
info = document.getElementById('about-content');
if (window.XMLHttpRequest)
{ xhr = new XMLHttpRequest(); }
else
{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
xhr.open("GET","rails/info/properties",false);
xhr.send("");
info.innerHTML = xhr.responseText;
info.style.display = 'block'
}
</script>
<script type="text/javascript">
alert('Start of JSON Routine');
$(document).ready( function() {
alert('Attach a JQuery Live event to the button');
$('#getdata-button').live('click', function() {
alert("Get JSON data");
$.getJSON('http://0.0.0.0:3000/getjson/1', function(data) {
alert('Processing returned JSON data');
var tmp = '<table border=1>';
for (i=0;i<data.length;i++)
{
tmp = tmp +'<tr>';
tmp = tmp + '<td>' + data[i].book.price + '</td>';
tmp = tmp + '<td>' + data[i].book.title + '</td>';
tmp = tmp + '<td>' + data[i].book.author + '</td>';
tmp = tmp + '<td>' + data[i].book.ISBN + '</td>';
tmp = tmp + '<td>' + data[i].book.yearPublished + '</td>';
tmp = tmp + '<td>' + data[i].book.volume + '</td>';
tmp = tmp + '<td>' + data[i].book.publisher + '</td>';
tmp = tmp + '<td>' + data[i].book.edition + '</td>';
tmp = tmp + '<td>View</td>';
tmp = tmp + '</tr>';
}
tmp = tmp + '</table>';
alert('About to insert Table into DOM in content Div');
$('#showdata').html(tmp);
}); //getJSON end
}); //getdata-button end
}); //document.ready end
alert('End of JSON routine');
</script>
</head>
<body>
<div id="page">
<div id="sidebar">
<ul id="sidebar-items">
<li>
<h3>Browse the documentation</h3>
<ul class="links">
<li>Rails API</li>
<li>Ruby standard library</li>
<li>Ruby core</li>
<li>Rails Guides</li>
</ul>
</li>
</ul>
</div>
Get JSON Data
<script>alert("Before the JMC div");</script>
<div id="showdata">JMC</div>
<script>alert("Past the JMC div");</script>
<div id="content">
<h1>Welcome aboard</h1>
<h2>You’re riding Ruby on Rails!</h2>
</div>
<div id="about">
<h3>About your application’s environment</h3>
<div id="about-content" style="display: none"></div>
</div>
<div id="getting-started">
<h1>Getting started</h1>
<h2>Here’s how to get rolling:</h2>
<ol>
<li>
<h2>Use <code>rails generate</code> to create your models and controllers</h2>
<p>To see all available options, run it without parameters.</p>
</li>
<li>
<h2>Set up a default route and remove or rename this file</h2>
<p>Routes are set up in config/routes.rb.</p>
</li>
<li>
<h2>Create your database</h2>
<p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p>
</li>
</ol>
</div>
</div>
<div id="footer"> </div>
</div>
</body>
</html>
Here is the JSON data I get back when I just invoked the URL/ Controller action directly from the browser:
[
{
"book":{
"price":"25.52",
"created_at":"2011-10-27T22:35:04Z",
"ISBN":"",
"author":"Obie Fernandez",
"title":"Rails 3 Way, The (2nd Edition)",
"updated_at":"2011-10-27T22:35:04Z",
"yearPublished":"2010",
"id":1,
"publisher":"Addison-Wesley",
"volume":"2",
"edition":"second edition"
}
},
{
"book":{
"price":"23.94",
"created_at":"2011-10-27T22:39:37Z",
"ISBN":"",
"author":"Michael Hartl",
"title":"Ruby on Rails 3 Tutorial: Learn Rails by Example",
"updated_at":"2011-10-27T22:39:37Z",
"yearPublished":"2010",
"id":2,
"publisher":"Addison-Wesley",
"volume":"",
"edition":"first edition"
}
},
{
"book":{
"price":"24.97",
"created_at":"2011-10-27T22:42:42Z",
"ISBN":"",
"author":"Cloves Carneiro Jr. and Rida Al Barazi",
"title":"Beginning Rails 3 ",
"updated_at":"2011-10-27T22:42:42Z",
"yearPublished":"2009",
"id":3,
"publisher":"Apress",
"volume":"",
"edition":"first edition"
}
}
]
Anything else that might be useful. The Rails logs show the request being handled correctly.
When I step through the script, the alerts come up in a starnge sequence:
THe first alert I get is "Here at start of JSON Routine", followed by "Finished document ready routine" and then "Attach a JQuery Live event to the button". I then click the button for getdata and then a # appears at the end of the URL and then nothing.
MOved the script into the head - same outcome.
SWitched #content to #showdata - same outcome.
Final Edit:
The problem is solved thanks to the input of many people.
There were a number of issues, but the final issue was a same origin error in that the URL on the getJSON request was different to the URL making the request. The request had 0.0.0.0:3000/getjson/1 whereas the requesting URL was localhost:3000/getjson/1. Very hard to spot and the lack of return / status info with getJSON made it more difficult. Anyway thanks is due to all contributors, who all made valid contributions. I hope I have the expertise to contribute myself someday.
This is most related to same origin policy (cross domain blocking) and can be resolved by using a JSONP call. Add a ?callback=? to the end of the URL:
$(document).ready( function() {
alert('Attach a JQuery Live event to the button');
$('#getdata-button').live('click', function() {
$.getJSONP('http://0.0.0.0:3000/getjson/1?callback=?, function(data) {
// ... Omiting for brevity
$('#content').html(tmp);
});
});
});
Alright Joe, you need to start with the simplest case possible... clean up all of your HTML and get rid of everything that you do not need. I tested this and verified that it works on my local Rails server.
I mocked up the Rails controller action to return your JSON data using:
def getjson
json_data = '[{ "book": { "price": 18.75, "title": "Moby Dick", "author": "Herman Melville", "ISBN": "0393972836", "yearPublished": 2001, "volume": 1, "publisher": "W. W. Norton & Company", "edition": "2nd Edition" }}]'
render :json => json_data, :status => :ok
end
You shouldn't need to change your Rails controller code since you said it was working. I just wanted to show you how I mocked it up for your future reference.
Now, replace the contents of your HTML file with this:
<!DOCTYPE html>
<html>
<head>
<title>JSON Test example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#getdata-button').live('click', function() {
// clear out the old data:
$('#content').html('');
alert("Getting JSON data");
$.ajax({
dataType: 'json',
type: 'GET',
url: '/getjson/1',
success: function(json) {
console.log(json);
alert('Processing returned JSON data');
var tmp = '<table border=1>';
for (i = 0; i < json.length; i++) {
tmp = tmp + '<tr>';
tmp = tmp + '<td>' + json[i].book.price + '</td>';
tmp = tmp + '<td>' + json[i].book.title + '</td>';
tmp = tmp + '<td>' + json[i].book.author + '</td>';
tmp = tmp + '<td>' + json[i].book.ISBN + '</td>';
tmp = tmp + '<td>' + json[i].book.yearPublished + '</td>';
tmp = tmp + '<td>' + json[i].book.volume + '</td>';
tmp = tmp + '<td>' + json[i].book.publisher + '</td>';
tmp = tmp + '<td>' + json[i].book.edition + '</td>';
tmp = tmp + '<td>View</td>';
tmp = tmp + '</tr>';
}
tmp = tmp + '</table>';
alert('About to insert the following data into DOM: ' + tmp);
// Show the div we are looking for in the browser's console
console.log($('#content'));
$('#content').html(tmp);
},
error: function(response) {
alert('There was an error: ' + response.status);
}
}); // $.ajax end
}); //getdata-button end
}); //document.ready end
</script>
</head>
<body>
Get JSON Data
<br/><br/>
<div id="content">The data will be placed here.</div>
</body>
</html>
Notice that I am using the $.ajax method which allows me to specify an error handler callback. I would recommend using this way of doing things until you become more familiar with jQuery and feel confident that you can start using the other AJAX helpers.
I hope this helps!
Your page is being refreshed and the data is likely getting dropped. Try:
$('#getdata-button').live('click', function(evt) {
evt.preventDefault();
}
$('#content') doesn't seem to exist.
EDIT
After another look, it seems to problem hinges on the button click event not firing. Since this is added via live, and as another user has posted, works on jsfiddle: I wonder what version of jQuery you are using? Looks like it could be very old indeed. Try upgrading to a newer version.

Categories