Why isn't my JavaScript able to output my element? - javascript

I am currently trying to randomize the ads that show up on this website with JavaScript. In order to do this I am importing two script files.
The issue is I can not get the image to load, and I am unsure as to whether it's a problem with the parameters I have set or an error in the format of "" and '' when trying to output the element. I have already attempted to preset the variable that belongs as the url with no luck. The line code I tried with this attempt was var img = "ad" + rNumber + ".jpg"; Below is the HTML code with the embedded JavaScript that I am working on. Any help with this problem would be greatly appreciated.
function randInt(n) {
randNum = Math.ceil(Math.random() * n);
return randNum;
}
function adDescription(n) {
var descrip = new Array();
descrip[1] = "[AD] Diamond Health Club - For all your Health Club Needs";
descrip[2] = "[AD] Pixal - Quality Digital Equipment and Accessories";
descrip[3] = "[AD] dHome - Quality Geodesic Domes and Homes";
descrip[4] = "[AD] Dunston Retreat Center - get away";
descrip[5] = "[AD] LanGear - Quality Network Solutions for all your Business Needs";
return descrip[n];
}
function adLink(n) {
var link = new Array();
link[1] = "http://www.diamondhealth.com";
link[2] = "http://www.pixalproducts.com";
link[3] = "http://www.dhome.com";
link[4] = "http://www.dunstonretreats.com";
link[5] = "http://wwww.langearproducts.com";
return link[n];
}
<html>
<head>
<!--
New Perspectives on HTML and CSS
Tutorial 10
Case Problem 2
The Ridgewood Herald Tribune
Author: Brigitte Arcoite
Date: 7-31-17
Filename: front.htm
Supporting files: ads1.jpg - ads5.jpg, ads.js, fp.jpg, logo.jpg,
modernizr-1.5.js, random.js, styles.css
-->
<meta charset="UTF-8" />
<title>The Ridgewood Herald Tribune</title>
<script src="modernizr-1.5.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
<script src="random.js" type="text/javascript"></script>
<script src="ads.js" type="text/javascript"></script>
</head>
<body>
<nav>
<h1>Contents</h1>
<p class="section">Main</p>
<ul>
<li>Home</li>
<li>Subscriptions</li>
<li>Contact Us</li>
<li>News Sources</li>
</ul>
<p class="section">News</p>
<ul>
<li>Local</li>
<li>National</li>
<li>International</li>
</ul>
<p class="section">Sports</p>
<ul>
<li>Baseball</li>
<li>Basketball</li>
<li>Football</li>
<li>Golf</li>
<li>Hockey</li>
<li>Miscellaneous</li>
</ul>
<p class="section">Opinion</p>
<ul>
<li>Editorials</li>
<li>Columnists</li>
<li>Letters</li>
</ul>
<p class="section">Classifieds</p>
<ul>
<li>Employment</li>
<li>For Sale</li>
<li>Personals</li>
<li>Real Estate</li>
<li>Wanted</li>
</ul>
<p class="section">Other</p>
<ul>
<li>Business</li>
<li>Weather</li>
<li>Entertainment</li>
</ul>
</nav>
<section>
<div id="ads">
<script>
var rNumber = randInt(5); //generate a random integer from 1 to 5
var rAd = adDescription(descrip[rNumber]); //description of the random ad
var rLink = adLink(link[rNumber]); //url of the random ad
var img = "ad" + rNumber + ".jpg";
alert(rNumber);
document.write("<a href='" + rLink + "'>");
document.write("<img src='" + img + "' alt='" + rAd + "' />");
document.write("</a>");
</script>
</div>
<div id="request">Contact us today to place your ad</div>
<header><img src="logo.jpg" alt="Ridgewood Herald Tribune" /></header>
<img src="fp.jpg" alt="" id="fp" />
<h2>Park Opens</h2>
<p>The <i>Adventure Island</i> theme park opened its doors on Monday near Ridgewood. The park, one of the biggest in New Jersey, drew large crowds, but the long lines didn't deter anyone. "I've been watching them put up the rides over the last year,
it's really exciting to finally get inside the gates!" said Ridgewood resident Denise Brooks.
</p>
<p class="cont">story continues on page 2...</p>
<footer>
<address>
<b>Ridgewood Herald Tribune</b> ° 10010 Atwood Ave.
° Ridgewood, NJ 07451<br />
Phone: (201)555-1101 ° Fax: (201)555-1102
</address>
</footer>
</section>
</body>
</html>

Your variable randNum isn't defined. You're also getting the ol' Uncaught Reference error (randInt [function] not defined). Perhaps add an event listener to your scripts to ensure they run when the DOM Content is loaded
<script>
document.addEventListener("DOMContentLoaded", function(event) {
//console.log("DOM fully loaded and parsed");
do stuff here
});
</script>
Hope this helps

Related

Linking an object to a jquery function

I am trying to link together an object in JS to a function of a button in Jquery. I've linked Jquery to my HTML so it is technically working, however, it's a specific project that is requiring the buttons to display the info. in the object. I've tried editing it on my own and I keep getting stuck and I'm not sure how to link the two. The instructions are included as well.
// create a JavaScript object here with the following fields: firstName, lastName, jobTitle, homeOffice
function About(firstName, lastName, jobTitle, homeOffice, tellMeMore) {
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
this.homeOffice = homeOffice;
this.tellMeMore = tellMeMore;
};
var about01 = new About("Megan", "Adams", "Customer Serice Rep", "Penn Field", "I have been working at in customer service since December 2018 and transferred over to the Resolutions Department in fall of 2018. In my spare time I love watching scary movies, listening to true crime podcasts and music, and making art.");
// using jQuery and the object above, display the information as the appropriate button is clicked
var button = document.querySelectorAll ('button');
$(document).ready(function() {
$(".button").click(function() {
$(".name").fadeToggle(1000);
});
});
$(document).ready(function() {
$(".button1").click(function() {
$(".job").fadeToggle(1000);
});
});
$(document).ready(function() {
$(".button2").click(function() {
$(".office").fadeToggle(1000);
});
});
$(document).ready(function() {
$(".button3").click(function() {
$(".more").fadeToggle(1000);
});
});
<!DOCTYPE html>
<html>
<head>
<title role="title">CEP Engineering Application</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<article>
<header role=banner>
<h1>About Me</h1>
</header>
<img src="img/IMG_1989.jpg" alt="Megan Adams Picture" style="width:250px;height:460px; "class="img">
<section>
<button type="button" class="button">Name</button>
<p class="name">Megan Adams</p>
</section>
<section>
<button type="button" class="button1">Job Title</button>
<p class="job">Customer Service Reo</p>
</section>
<section>
<button type="button" class="button2">Home Office</button>
<p class="office">Penn Field</p>
</section>
<section>
<button type="button" class="button3">Tell Me More</button>
<p class="more">I have been working at in customer service since December 2018 and transferred over to the Resolutions Department in fall of 2018. In my spare time I love watching scary movies, listening to true crime podcasts and music, and making art. </p>
</section>
<script src="init.js"></script>
</article>
</body>
</html>
I have edited both the code and html and made them much smaller.
now have a look at attribute data and read the comment to understand, how this work.
// create a JavaScript object here with the following fields: firstName, lastName, jobTitle, homeOffice
function About(firstName, lastName, jobTitle, homeOffice, tellMeMore) {
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
this.homeOffice = homeOffice;
this.tellMeMore = tellMeMore;
};
var about01 = new About("Megan", "Adams", "Customer Serice Rep", "Penn Field", "I have been working at in customer service since December 2018 and transferred over to the Resolutions Department in fall of 2018. In my spare time I love watching scary movies, listening to true crime podcasts and music, and making art.");
// using jQuery and the object above, display the information as the appropriate button is clicked
var button = document.querySelectorAll ('button');
$(document).ready(function() {
// present the values,
$("section > p").each(function(){
// more dynamic approch
var field = $(this).attr("data");
var value ="";
if (field){
field.split(" ").forEach((x)=> {
if (value== "")
value = about01[x];
else value += " " + about01[x] // firstName and lastName
});
$(this).html(value)
}
});
// now you only need one method click to display toggle p
$(".button").click(function() {
// you know that p exist under button
// so go back to parent of the current object and then find the p and toggle it.
$(this).parent().find("p").fadeToggle(1000);
});
});
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<article>
<header role=banner>
<h1>About Me</h1>
</header>
<img src="img/IMG_1989.jpg" alt="Megan Adams Picture" style="width:250px;height:460px; "class="img">
<section>
<button type="button" class="button">Name</button>
<p data="firstName lastName" ></p>
</section>
<section>
<button type="button" class="button">jobTitle</button>
<p data="jobTitle"></p>
</section>
<section>
<button type="button" class="button">homeOffice</button>
<p data="homeOffice"></p>
</section>
<section>
<button type="button" class="button">Tell Me More</button>
<p data="tellMeMore"> </p>
</section>
<script src="init.js"></script>
</article>
Only a single jQuery() is necessary. You can use get the property names of the object using Array.prototype.keys() convert the className of current element .toLowerCase() within .html(), .filter() the property names where .indexOf() className of the current element is greater than -1, .map() and .join() the result
$(function() {
function About(firstName, lastName, jobTitle, homeOffice, tellMeMore) {
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
this.homeOffice = homeOffice;
this.tellMeMore = tellMeMore;
};
const about01 = new About("Megan", "Adams", "Customer Serice Rep", "Penn Field", "I have been working at in customer service since December 2018 and transferred over to the Resolutions Department in fall of 2018. In my spare time I love watching scary movies, listening to true crime podcasts and music, and making art.");
const keys = Object.keys(about01);
$(".name, .job, .office, .more").html(function() {
const el = this;
return keys.filter(function(value) {
return value.toLowerCase()
.indexOf(el.className) > -1
})
.map(function(value) {
return about01[value]
}).join(" ")
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<body>
<div class="name"></div>
<div class="job"></div>
<div class="office"></div>
<div class="more"></div>
</body>
You only need to use one document.ready method in your JS.
What you can do to achieve this is add a click event listener to all your buttons. Then when a button is clicked you can refer to the button clicked using $(this). The element which you want to append text to is the paragraph next to the button clicked. You can get the paragraph element by using $(this).next('p'). Using the class name of the paragraph you can then work out which object property to display.
Below, I have used an object called classToProp which maps your class names to strings retrieved from your About object. Using this you can display the specific information you want to the adjoining p tag.
See working example below:
function About(firstName, lastName, jobTitle, homeOffice, tellMeMore) {
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
this.homeOffice = homeOffice;
this.tellMeMore = tellMeMore;
};
var about01 = new About("Megan", "Adams", "Customer Serice Rep", "Penn Field", "I have been working at in customer service since December 2018 and transferred over to the Resolutions Department in fall of 2018. In my spare time I love watching scary movies, listening to true crime podcasts and music, and making art.");
var classToProp = {
name: about01.firstName + " " + about01.lastName,
job: about01.jobTitle,
office: about01.homeOffice,
more: about01.tellMeMore
}
$(document).ready(function() {
$("button").click(function() {
var nextP = $(this).next('p');
var className = nextP.attr("class");
var txt = nextP.text(); // get the text from the paragraph
nextP.text(txt ? "" : classToProp[className]); // if the text is empty, display the associated property from your object, otherwise, if it already has text make it empty - this allows for a toggle effect
});
})
<!DOCTYPE html>
<html>
<head>
<title role="title">CEP Engineering Application</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<article>
<header role=banner>
<h1>About Me</h1>
</header>
<img src="img/IMG_1989.jpg" alt="" style="width:250px;height:460px; " class="img">
<section>
<button type="button" class="button">Name</button>
<p class="name"></p>
</section>
<section>
<button type="button" class="button1">Job Title</button>
<p class="job"></p>
</section>
<section>
<button type="button" class="button2">Home Office</button>
<p class="office"></p>
</section>
<section>
<button type="button" class="button3">Tell Me More</button>
<p class="more"></p>
</section>
<script src="init.js"></script>
</article>
</body>
</html>
Do you want something like below using jQuery $(selector).html(value);
// create a JavaScript object here with the following fields: firstName, lastName, jobTitle, homeOffice
function About(firstName, lastName, jobTitle, homeOffice, tellMeMore) {
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
this.homeOffice = homeOffice;
this.tellMeMore = tellMeMore;
};
var about01 = new About("Megan", "Adams", "Resolutions Specialist", "Penn Field", "I have been working at HomeAway in customer service since December 2018 and transferred over to the Resolutions Department in fall of 2018. In my spare time I love watching scary movies, listening to true crime podcasts and music, and making art.");
$(".name").html(`${about01.firstName} ${about01.lastName}`);
$(".job").html(about01.jobTitle);
$(".office").html(about01.homeOffice);
$(".more").html(about01.tellMeMore);
// using jQuery and the object above, display the information as the appropriate button is clicked
var button = document.querySelectorAll('button');
$(document).ready(function() {
$(".button").click(function() {
$(".name").fadeToggle(1000);
});
});
$(document).ready(function() {
$(".button1").click(function() {
$(".job").fadeToggle(1000);
});
});
$(document).ready(function() {
$(".button2").click(function() {
$(".office").fadeToggle(1000);
});
});
$(document).ready(function() {
$(".button3").click(function() {
$(".more").fadeToggle(1000);
});
});
button {
display: block;
}
<!DOCTYPE html>
<html>
<head>
<title role="title">CEP Engineering Application</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<article>
<header role=banner>
<h1>About Me</h1>
</header>
<img src="img/IMG_1989.jpg" alt="Megan Adams Picture" style="width:250px;height:460px; " class="img">
<section>
<button type="button" class="button">Name</button>
<p class="name">Megan Adams</p>
</section>
<section>
<button type="button" class="button1">Job Title</button>
<p class="job">Customer Service Reo</p>
</section>
<section>
<button type="button" class="button2">Home Office</button>
<p class="office">Penn Field</p>
</section>
<section>
<button type="button" class="button3">Tell Me More</button>
<p class="more">I have been working at in customer service since December 2018 and transferred over to the Resolutions Department in fall of 2018. In my spare time I love watching scary movies, listening to true crime podcasts and music, and making art. </p>
</section>
<script src="init.js"></script>
</article>
</body>
</html>

displaying an image on html with a json file

I am trying to store an image in a json object and display it on a html page with the rest of the data in the object. The image is stored locally in a folder called images. I have some code, but it doesnt seem to work... Can anyone please advise?
"photo":"<img src=images/audir8.jpg"
their is missing a closing ">" tag
Update you json like this
{
"id":2,
"name":"Audi A4",
"make":"Audi",
"model":"A4",
"enginesize":"1968cc",
"power":"140 BHP",
"acceleration":"7.8 seconds",
"topspeed":"139 MPH",
"drivetrain":"Front-wheel drive",
"specification":"Sat Nav, Heated Seats, Convertible, Immobiliser, Traction Control, Metallic paint, Airbags, LED lights",
"photo":"images/audir8.jpg"
}
html
<h1 id="title"></h1>
<ul>
<h2>Performance</h2>
<ul id="make"></ul>
<ul id="model"></ul>
<ul id="enginesize"></ul>
<ul id="power"></ul>
<ul id="acceleration"></ul>
<ul id="topspeed"></ul>
<ul id="drivetrain"></ul>
<ul id="specification"></ul>
<ul ><img id="photo" />
</ul>
</ul>
<script src="js/details.js"></script>
</div>
</div>
javascript
function populateContent(car)
{
titleEl=document.getElementById("title");
makeEL=document.getElementById("make");
modelEl=document.getElementById("model");
enginesizeEl=document.getElementById("enginesize");
powerEl=document.getElementById("power");
accelerationEl=document.getElementById("acceleration");
topspeedEl=document.getElementById("topspeed");
drivetrainEl=document.getElementById("drivetrain");
specificationEl=document.getElementById("specification");
photoEl=document.getElementById("photo");
//document.getElementById("imageid").src="../images/audir8.png";
titleEl.innerHTML = car.name;
makeEL.innerHTML = "<b>Make: </b>"+car.make;
modelEl.innerHTML = "<b>Model: </b>"+car.model;
enginesizeEl.innerHTML = "<b>Engine Size: </b>"+car.enginesize;
powerEl.innerHTML = "<b>Power: </b>"+car.power;
accelerationEl.innerHTML = "<b>0-60: </b>"+car.acceleration;
topspeedEl.innerHTML = "<b>Top Speed: </b>"+car.topspeed;
drivetrainEl.innerHTML = "<b>Drivetrain: </b>"+car.drivetrain;
specificationEl.innerHTML = "<h2>Specification: </h2>"+car.specification;
photoEl.src= car.photo;
}
You are missing the closing of image tag />. Add that and it will work. For demonstration I have used a live URL for the image. You can replace that with yours. Also, <ul> has <li> elements so replace that too.
var jsonData = {
"id":2,
"name":"Audi A4",
"make":"Audi",
"model":"A4",
"enginesize":"1968cc",
"power":"140 BHP",
"acceleration":"7.8 seconds",
"topspeed":"139 MPH",
"drivetrain":"Front-wheel drive",
"specification":"Sat Nav, Heated Seats, Convertible, Immobiliser, Traction Control, Metallic paint, Airbags, LED lights",
"photo":"<img src=http://myanmareiti.org/sites/default/files/styles/medium_retina/public/sample-5_0.jpg?itok=wn8qRWZM />"
};
function populateContent(car)
{
titleEl=document.getElementById("title");
makeEL=document.getElementById("make");
modelEl=document.getElementById("model");
enginesizeEl=document.getElementById("enginesize");
powerEl=document.getElementById("power");
accelerationEl=document.getElementById("acceleration");
topspeedEl=document.getElementById("topspeed");
drivetrainEl=document.getElementById("drivetrain");
specificationEl=document.getElementById("specification");
photoEl=document.getElementById("photo");
//document.getElementById("imageid").src="../images/audir8.png";
titleEl.innerHTML = car.name;
makeEL.innerHTML = "<b>Make: </b>"+car.make;
modelEl.innerHTML = "<b>Model: </b>"+car.model;
enginesizeEl.innerHTML = "<b>Engine Size: </b>"+car.enginesize;
powerEl.innerHTML = "<b>Power: </b>"+car.power;
accelerationEl.innerHTML = "<b>0-60: </b>"+car.acceleration;
topspeedEl.innerHTML = "<b>Top Speed: </b>"+car.topspeed;
drivetrainEl.innerHTML = "<b>Drivetrain: </b>"+car.drivetrain;
specificationEl.innerHTML = "<h2>Specification: </h2>"+car.specification;
photoEl.innerHTML = "<h2>photo: </h2>"+car.photo;
}
populateContent(jsonData);
<h1 id="title"></h1>
<ul>
<h2>Performance</h2>
<li id="make"></li>
<li id="model"></li>
<li id="enginesize"></li>
<li id="power"></li>
<li id="acceleration"></li>
<li id="topspeed"></li>
<li id="drivetrain"></li>
<li id="specification"></li>
<li id="photo"></li>
</ul>

JavaScript website problems

I'm learning how to build a website and I am having problems with the following
code. I can't figure out what is going on with it at all. I'm using visual studio code to write this in.
var HtmlCode = {
GetMenuItem:function(item){
let plg = item.choices[0];
let prg = item.choices[1];
let lbl_plg = '${item.type} - ${item.name} - ${plg.size}';
let lbl_prg = '${item.type} - ${item.name} - ${prg.size}';
return '<div class= "menu-item"> <div><div><img src="${item.img}"></div><div>${item.name}</div> </div><div>${item.descr}</div> <div> <div act="add2order" id="${plg.id}" cost="${plg.cost}" lbl="${plg_lbl}" title="Click to order">${plg.txt}</div> <div act="add2order" id="${prg.id}" cost="${prg.cost}" lbl="${prg_lbl}" title="Click to order">${prg.txt}</div> </div> </div>';
}
}
When I clean up the (return) and put it so I don't have to scroll to the right I get all sorts of errors in the visual studio code editor. I have it all together now on one line as shown in the example and it returns something but it won't return the menu items. I get all the items such as ${item.name} etc. but no img or any thing from my menu.
var App = {
Menu:null,
Init:function(){
this.Menu = JoesPizza.Menu;
$("#PizzaOrderSubmit").click(this.OrderNext);
},
LoadMenu:function(){
$("#MenuItemList").html("");
this.Menu.items.forEach(item => {
let html = HtmlCode.GetMenuItem(item);
$("#MenuItemList").append(html);
});
// attach click events to new menu items
}
}
var JoesPizza = JoesPizza||{};
JoesPizza.Menu = {"items":[
{"type":"Pizza", "name":"Cheese", "descr":"Marinara sauce topped with whole milk mozzarella cheese.",
"choices":[{"id":"pizza-cheese-lg", "size":"Large", "cost":22.99, "txt":"Large: $22.99"},
{"id":"pizza-cheese-rg", "size":"Regular", "cost":18.99, "txt":"Regular: $18.99"}],
"img":"/imgs/cheese.png"},
{"type":"Pizza", "name":"Pepperoni", "descr":"Marinara sauce with authentic old-world style pepperoni.",
"choices":[{"id":"pepp-lg", "size":"Large", "cost":23.99, "txt":"Large: $23.99"},
{"id":"pepp-rg", "size":"Regular", "cost":19.99, "txt":"Regular: $19.99"}],
"img":"/imgs/pepperoni.png"},
{"type":"Pizza", "name":"Meat Lover's", "descr":"Marinara sauce, authentic pepperoni, natural Italian sausage, roasted ham, smoked bacon, pork and beef.",
"choices":[{"id":"meat-lg", "size":"Large", "cost":23.99, "txt":"Large: $23.99"},
{"id":"meat-rg", "size":"Regular", "cost":19.99, "txt":"Regular: $19.99"}],
"img":"/imgs/meat.png"},
{"type":"Pizza", "name":"Supreme", "descr":"Marinara sauce, pepperoni, pork, beef,fresh mushrooms, fresh green bell peppers and fresh red onions.",
"choices":[{"id":"supr-lg", "size":"Large", "cost":23.99, "txt":"Large: $23.99"},
{"id":"supr-rg", "size":"Regular", "cost":19.99, "txt":"Regular: $19.99"}],
"img":"/imgs/supreme.png"},
{"type":"Wings", "name":"Traditional Bone-in", "descr":"Classic, juicy bone-in wings served perfectly crispy and tossed in your choice of signature sauce.",
"choices":[{"id":"wings-trad-12", "size":"12 Pieces", "cost":11.99, "txt":"12 Wings: $11.99"},
{"id":"wings-trad-08", "size":"8 Pieces", "cost":8.99, "txt":"8 Wings: $8.99"}],
"img":"/imgs/wings.png"}
]};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8"/>
<title>Joe's Pizza</title>
<link type="text/css" rel="stylesheet" href="/css/app.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/menu.js"></script>
<script type="text/javascript" src="/js/html-templates.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
</head>
<body>
<!-- top banner -->
<div class="page-top">
<img src="/imgs/pizza.png" title="Pizza Picture"/>
<span>joe's pizza</span>
<a href="/">
<img src="/imgs/home.png"></a>
</div>
<!-- page body -->
<div class="page-body">
<div class="side-left">
<div id="PizzaMenuHtml">
<fieldset id="PizzaMenu">
<legend>menu</legend>
<div id="MenuItemList">
</div>
</fieldset>
</div>
</div>
<div class="side-right">
<fieldset id="PizzaOrder">
<legend>your order</legend>
<div id="PizzaOrderItems">
</div>
<div id="PizzaOrderSummary">
<div>Order Total:</div>
<div></div>
</div>
<div id="PizzaOrderSubmit">Next >>></div>
</fieldset>
</div>
</div>
<div class="page-footer">
</div>
<script type="text/javascript">
App.Init();
App.LoadMenu();
</script>
</body>
</html>
When I clean up the (return) and put it so I don't have to scroll to the right I get all sorts of errors in the visual studio code editor.
Strings, like in your return, must start and end on the same line. New syntax allows this now, but you have to surround your string with ` a backtick. This is all explained here: Creating multiline strings in JavaScript
It appears you meant to use backticks in that first block since you also used template substitution syntax - which also only work inside backticks.
Perhaps when you change all those single quotes with backticks it will work, and you make your return more readable.

Why isn't this XSS attack functioning?

Background
I'm building up a website that lists organisations in my local area. The site is powered by an API and stores it's data in an instance of MongoDB.
I'm fetching JSON from the API and dynamically building the content in Javascript.
Now to test against XSS attacks I deliberately added some code to inject a Javascript alert into my page.
But it's not working? Which obviously I'm happy about but I'm more confused as to why not.
The JSON
{
"_created": "Tue, 11 Mar 2014 19:27:30 GMT",
"_etag": "fd8102613204000414cceff538771453b984a2c6",
"_id": "531f63a246e29300025291ba",
"_updated": "Tue, 11 Mar 2014 19:27:30 GMT",
"description": "<script>alert('hello');</script>",
"tags": [
"Antiques"
],
"title": "HTML Injection",
"url": "www.link.com"
}
the injected code
<script>alert('hello');</script>
The code to retrieve the JSON and render it
function S_GET(id) {
var a = new RegExp(id+'=([^&#=]*)');
return decodeURIComponent(a.exec(window.location.search)[1]);
}
// retrieves languages and adds them to a list
var organisationId = S_GET('organisationId');
var url = 'http://damp-island-8192.herokuapp.com/organisations/' + organisationId;
var dataRequest = new XMLHttpRequest();
dataRequest.open('GET',url, false);
dataRequest.onreadystatechange = processJSON;
dataRequest.send();
function processJSON() {
if ( dataRequest.readyState == 4 && dataRequest.status == 200 ) {
showJSON(dataRequest.responseText);
}
}
function showJSON(input) {
//dom elements
var list = document.createElement('ul');
list.setAttribute('id', 'organisation-details-list');
var organisation = JSON.parse(input);
// list organisation details
// title
var title = document.createElement('li');
title.setAttribute('class', 'organisation-title');
title.innerHTML = organisation.title;
list.appendChild(title);
// description
var desc = document.createElement('li');
desc.setAttribute('class', 'organisation-desc');
desc.innerHTML = organisation.description;
list.appendChild(desc);
// link
var link = document.createElement('li');
link.setAttribute('class', 'organisation-link');
var a = document.createElement('a');
a.setAttribute('href', organisation.url);
a.innerHTML = organisation.url;
link.appendChild(a);
list.appendChild(link);
document.getElementsByClassName('organisation')[0].appendChild(list);
};
The HTML
<!DOCTYPE html>
<head>
<title>Moving To Leicester</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="container">
<div class="header">
<ul class="nav nav-pills dropdown-menu-right">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
<div class="row padding-top-5">
<div class="col-md-2">
<!--Sidebar content-->
</div>
<div class="col-md-10">
<!--Body content-->
<div class="organisation"></div>
</div>
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/organisation-details-page.js"></script>
</body>
</html>
Question
Why doesn't the page trigger an alert when I'm viewing it?
To my knowledge inserting executable Javascript via AJAX is somewhat limited.
You cannot just get code via AJAX, put it in a LI's innerHTML an have it executed.
This is what you do:
var organisation=JSON.parse(input);
var title=document.createElement('li');
title.setAttribute('class','organisation-title');
title.innerHTML=organisation.title;
list.appendChild(title);
However, one work-around could be if you change your injection into this:
<iframe src='/' width='1' height='1' onload='window.alert("boo");'></iframe>
I think that would inject itself.

Setting a global variable for jquery to carry accross mutiple pages

Ok this is what I need to do. Not real sure how to do it. I have a php page running index.php is my main page that loads and brings in menu.php and a few other sub files. So here is my problem. I have a drop down menu written in java and then I also have a Jquery script linked in to generate a title for the page. Whats happening is when I click the link in the menu its showing the title for a minute and then vanishes because its going to a new page. If I add a return false its stops and works, but doesn't forward you to the new page of course. So here is my problem. I need to set a variable im assuming or something to hold that value of what is clicked and take it to the new page, which i'm not sure how to do. Here is my menu code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="main.css" />
<link rel="stylesheet" type="text/css" href="css/default.css">
<link rel="stylesheet" type="text/css" href="css/css-slider.css">
<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>
<script src="css/active.js" type="text/javascript">
</script>
<script src="css/drop1.js" type="text/javascript">
</script>
</script>
<!--Main Navigation Start -->
<div id="nav" class="nav">
<ul id="sddm">
<li><a class="navigation" value="home" id="Home" href="index.php" onMouseOver="mopen('m1')" onMouseOut="mclosetime()">Home</a>
<div id="m1" onMouseOver="mcancelclosetime()" onMouseOut="mclosetime()">
</div>
</li>
<li><a class="navigation" id="Station History" href="station_history.php" onMouseOver="mopen('m2')" onMouseOut="mclosetime()">Station History</a>
<div id="m2" onMouseOver="mcancelclosetime()" onMouseOut="mclosetime()">
</div>
</li>
<li>
<a class="navigation" id="Apparatus" href="Apparatus.php" onMouseOver="mopen('m3')" onMouseOut="mclosetime()">Apparatus</a>
<div id="m3" onMouseOver="mcancelclosetime()" onMouseOut="mclosetime()">
<a class="navigation" id="Truck History" href="truck_history.php">Truck History</a>
</div>
</li>
<li>
<a class="navigation" id="Photo Gallery" href="photos.php" onMouseOver="mopen('m4')" onMouseOut="mclosetime()">Photos</a>
<div id="m4" onMouseOver="mcancelclosetime()" onMouseOut="mclosetime()">
</div>
</li>
<li>
<a class="navigation" id="News & Events" href="news_events.php" onMouseOver="mopen('m5')" onMouseOut="mclosetime()">News & Events</a>
<div id="m5" onMouseOver="mcancelclosetime()" onMouseOut="mclosetime()">
</div>
</li>
<li>
<a class="navigation" id="Station Members" href="Station_members.php" onMouseOver="mopen('m6')" onMouseOut="mclosetime()">Station Members</a>
<div id="m6" onMouseOver="mcancelclosetime()" onMouseOut="mclosetime()">
</div>
</li>
<li>
<a class="navigation" id="Education" href="education.php" onMouseOver="mopen('m7')" onMouseOut="mclosetime()">Education</a>
<div id="m7" onMouseOver="mcancelclosetime()" onMouseOut="mclosetime()">
<a class="navigation" id="Station Tours" href="">Station Tours</a>
<a class="navigation" id="Fire Extinguisher" href="">Fire Extinguisher</a>
<a class="navigation" id="First Aid & CPR" href="">First Aid & CPR</a>
<a class="navigation" id="Smoke Alarms" href="">Smoke Alarms</a>
</div>
</li>
<li>
<a class="navigation" id="Contact Us" href="contactus.php" onMouseOver="mopen('m8')" onMouseOut="mclosetime()">Contact Us</a>
<div id="m8" onMouseOver="mcancelclosetime()" onMouseOut="mclosetime()"> </div>
</li>
</ul>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
Here is my Jquery
//navigation
$(document).ready(function () {
//var mname = ($(this).attr('id'));
$("a.navigation").click(function () {
//alert($(this).attr('id'));
$("span#title").html($(this).attr('id'));
})
});
and here is my drop down
<!--
var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;
// open hidden layer
function mopen(id)
{
// cancel close timer
mcancelclosetime();
// close old layer
if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
// get new layer and show it
ddmenuitem = document.getElementById(id);
ddmenuitem.style.visibility = 'visible';
}
// close showed layer
function mclose()
{
if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}
// go close timer
function mclosetime()
{
closetimer = window.setTimeout(mclose, timeout);
}
// cancel close timer
function mcancelclosetime()
{
if(closetimer)
{
window.clearTimeout(closetimer);
closetimer = null;
}
}
// close layer when click-out
document.onclick = mclose;
// -->
I am completely stumpped for some reason on how to do this and really would appreciate the help.
Global variables last only for the lifetime of a given page so they will not last across multiple pages. So, to pass data from one page to another, you have to store the data somewhere in the browser or server so it can be retrieved by subsequent pages.
Your options for storing or passing the data in the browser are:
Store the data in a cookie and then retrieve it from the cookie on subsequent pages.
Store the data in local storage and then retrieve from local storage on subsequent pages.
When going to the next page, encode the data in the URL you are going to (either as a query parameter or as a hash value and then retrieve that data from the URL with javascript in the next page.
Options 1 and 2 are best for data that lots of pages need to access. Cookies are supported in all versions of all browsers (though occasionally users will block them). Local storage is a little cleaner API and is supported in all modern browsers, but is not supported in some older browsers. The amount of data that can be stored per domain is more limited in cookies than local storage.
Keep in mind that options 1 and 2 only work for pages in the same domain. Cookies and local storage cannot be accessed outside the domain that stored the data.
See this article on MDN for reading/writing cookies.
See this article on MDN for reading/write local storage, including a compatibility library that falls back to cookies if local storage is not available.
Use Cookies! Here is some Javascript:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name){
var i,x,y,ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++)
{
x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g,"");
if (x == c_name)
{
return unescape(y);
}
}
}

Categories

Resources