Why isn't this XSS attack functioning? - javascript

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.

Related

Javascript files not loading in HTML page

I have a folder structure like this:
I have referenced data.js and app.js like this:
but my HTML page does not display my data. I tried using the full file path as well but that does not seem to work either. I tried this ../../UFOs/static/js/data.js as well from another question
I think the error might be in my app.js file. I used console.log on internet explorer and it pointed to a syntax error on the highlighted line:
app.js
// import the data from data.js
const tableData = data;
// Reference the HTML table using d3
var tbody = d3.select("tbody");
function buildTable(data) {
data.forEach((dataRow) => {
let row = tbody.append("tr");
Object.values(dataRow).forEach((val) => {
let cell = row.append("td");
cell.text(val);
}
);
});
function handleClick() {
// Grab the datetime value from the filter
let date = d3.select("#datetime").property("value");
let filteredData = tableData;
// Check to see if a date was entered and filter the
// data using that date.
if (date) {
// Apply `filter` to the table data to only keep the
// rows where the `datetime` value matches the filter value
filteredData = filteredData.filter(row => row.datetime === date);
};
// Rebuild the table using the filtered data
// #NOTE: If no date was entered, then filteredData will
// just be the original tableData.
buildTable(filteredData);
};
// Attach an event to listen for the form button
d3.selectAll("#filter-btn").on("click", handleClick);
// Build the table when the page loads
buildTable(tableData);
data.js
var data = [
{
datetime: "1/1/2010",
city: "benton",
state: "ar",
country: "us",
shape: "circle",
durationMinutes: "5 mins.",
comments: "4 bright green circles high in the sky going in circles then one bright green light at my front door."
},
{
datetime: "1/1/2010",
city: "bonita",
state: "ca",
country: "us",
shape: "light",
durationMinutes: "13 minutes",
comments: "Three bright red lights witnessed floating stationary over San Diego New Years Day 2010"
}
];
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UFO Finder</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="static/css/style.css">
</head>
<body class="bg-dark">
<div class="wrapper">
<nav class="navbar navbar-dark bg-dark navbar-expand-lg">
<a class="navbar-brand" href="index.html">UFO Sightings</a>
</nav>
<div class="jumbotron">
<h1 class="display-4">The Truth Is Out There</h1>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<h3>UFO Sightings: Fact or Fancy? <small>Ufologists Weigh In</small></h3>
</div>
<div class="col-md-8">
<p>Some text</p>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
<form class="bg-dark">
<p>Filter Search</p>
<ul class="list-group bg-dark">
<li class="list-group-item bg-dark">
<label for="date">Enter Date</label>
<input type="text" placeholder="1/10/2010" id="datetime"/>
</li>
<li class="list-group-item bg-dark">
<button id="filter-btn" type="button" class="btn btn-dark" >Filter Table</button>
</li>
</ul>
</form>
</div>
<div class="col-md-9">
<table class="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>City</th>
<th>State</th>
<th>Country</th>
<th>Shape</th>
<th>Duration</th>
<th>Comments</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.js"></script>
<script type="text/javascript" src="./static/js/data.js"></script>
<script type="text/javascript" src="./static/js/app.js"></script>
</body>
</html>
add <tbody></tbody> after </thead> in your HTML.
While a <tbody> is not required under the HTML5 spec, your function attempts to append the new rows to that element, so without it, they cannot be displayed, which is the exact problem you are experiencing.
Alternatively, you could have modified your function to append the rows to the table itself.
const dataTable = d3.select('table');
function buildTable(data) {
data.forEach((dataRow) => {
let row = dataTable.append("tr");
Object.values(dataRow).forEach((val) => {
let cell = row.append("td");
cell.text(val);
});
});
}
You have syntax errors in app.js, try the below code. buildTable function doesn't have closing brackets.
// import the data from data.js
const tableData = data;
// Reference the HTML table using d3
var tbody = d3.select("tbody");
function buildTable(data) {
data.forEach((dataRow) => {
let row = tbody.append("tr");
Object.values(dataRow).forEach((val) => {
let cell = row.append("td");
cell.text(val);
});
});
}
function handleClick() {
// Grab the datetime value from the filter
let date = d3.select("#datetime").property("value");
let filteredData = tableData;
// Check to see if a date was entered and filter the
// data using that date.
if (date) {
// Apply `filter` to the table data to only keep the
// rows where the `datetime` value matches the filter value
filteredData = filteredData.filter(row => row.datetime === date);
}
// Rebuild the table using the filtered data
// #NOTE: If no date was entered, then filteredData will
// just be the original tableData.
buildTable(filteredData);
}
// Attach an event to listen for the form button
d3.selectAll("#filter-btn").on("click", handleClick);
// Build the table when the page loads
buildTable(tableData);

Second AJAX call not functioning

Last Update
I realized why I was getting undefined when I created the result2 variable I set it to undefined instead of let result2 = ''; setting it to a string. Once I made that adjustment the undefined went away. Final script.js is below.
Update 4
It finally works it came down to the following line which was incorrect document.querySelectorAll("weathers").innerHTML = result2; I had to go back and change weathers to an id and not a class and I had to change the line above to document.querySelector("#weathers").innerHTML += result2; and now it works. I just have to figure out on my own why I get an undefined in my code see image.
Update 3
I am down to my last portion which is I get the results I want if I console log my results which look like this:
With this line I am not getting anything in my html document.querySelectorAll("weathers").innerHTML = result2; I am going to try something else to see if I could get this to work. If you notice though I am getting an undefined in my code in the image does anyone know if that impacts why I am not getting any output? I get no error messages either.
UPDATE 2
I made the adjustments to eliminate too much code the updates code will just be in my script.js file listed below. I get the following output which is an array of objects:
When I run the code I get the following error message:
Uncaught TypeError: Cannot read property 'name' of undefined
at XMLHttpRequest.xhr2.onload (script.js:57) xhr2.onload # script.js:57 load (async) loadWeathers # script.js:33
I am going to work on the correct syntax to extract the information I need since it is now an array of objects and not just an object.
UPDATE 1
With a suggestion below I was able to finally get something to work off of. Now I can see that instead of giving me one city at a time it is putting all of the cities inside of the api request url and I get the following error message:
script.js:77 GET
http://api.openweathermap.org/data/2.5/weather?q=San_Francisco,Miami,New_Orleans,Chicago,New_York_City&APPID=XXXXXXXX
404 (Not Found)
Background:
I am learning about API's and am building a mini weather web app. I am learning the long way Vanilla Javascript before I move onto doing the same thing in Jquery.
Goal:
I would like to have two things going on at once:
When a user inputs a name of a city a card will pop up with weather information.
When a user visits the page there will be already about five major cities populated on the page like so:
What I have so far:
So far I have been able to build the functionality for the input so when a user inputs the name of the city a card will pop up on the page and looks like this:
I also have some code to get into the next topic which is my problem.
Problem:
I have added a second ajax call that contains an array of cities that will be added to the URL. I have added a second button ("Get Weathers") for testing purposes that when I click on the button all of the cities will pop up like in the first image. I have done some research but everything I find involves jquery and not vanilla javascript Ajax. I cannot figure out why nothing is populating. I have checked the console for errors and I am not getting any. When I check the network traffic I am not getting any call requests. I am not getting anything and I cannot figure out why.
Here is my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<LINK REL=StyleSheet HREF="style.css" TYPE="text/css">
<title>Current Weather App</title>
</head>
<body>
<main role="main">
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Today's Weather</h1>
<p class="lead text-muted">Curious about weather in your location? Just fill in below and submit.</p>
<p>
<div class="input-group mb-3">
<input type="text" class="form-control" id="city">
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="buttonW" type="button">Get Weather</button>
<button class="btn btn-outline-secondary" id="buttonW2" type="button">Get Weathers</button>
</div>
</div>
</p>
</div>
</section>
<div id="weather"></div>
<div class="album py-5 bg-light">
<div class="container">
<div class="row" id="weathers"></div>
</div>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>
<script src="script.js"></script>
</body>
</html>
Here is my FINAL script.js file:
// Create an event listener
document.getElementById("buttonW").addEventListener("click", loadWeather);
document.getElementById("buttonW2").addEventListener("click", loadWeathers);
///////////////THIS IS PART OF THE loadWeathers///////////////////////////////////////////////////////////////////////////////////////////
function getCity(locations) {
for (let i = 0; i < locations.length; i++) {
}
return locations;
}
function loadWeathers() {
let xhr2 = new XMLHttpRequest();
const cities = [
"5368361",
"4173495",
"4335045",
"4887398",
"5128638"
];
const base_path2 =
"http://api.openweathermap.org/data/2.5/group?id=" + getCity(cities) + "&APPID=XXXXXXXXXXXXXXXXXXXXXX";
xhr2.open("GET", base_path2, true);
xhr2.onload = function () {
if (this.status == 200) {
let cityWeathers2;
try {
cityWeathers2 = JSON.parse(this.responseText);
} catch (e) {
// JSON not valid, show error message
}
console.log(cityWeathers2)
// //add weather info
for (let i = 0; i < cities.length; i++) {
let result2 = '';
result2 +=
`<div class="col-md-4">
<div class="card mb-4 box-shadow">
<div class="card-body">
<h5 class="card-title">${cityWeathers2.list[i].name}</h5>
<p class="card-text">Here are some weather details for your City</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Weather: ${cityWeathers2.list[i].weather[0].main} <img class="card-img-top weather-icon" src="${getIconURL(cityWeathers2.list[i].weather[0].icon)}" alt="Card image cap"></li>
<li class="list-group-item">Temperature: ${convertKtoF(cityWeathers2.list[i].main.temp) }° </li>
<li class="list-group-item">Wind Speed: ${convertMPStoMPH(cityWeathers2.list[i].wind.speed) } </li>
<li class="list-group-item">Geo Location: ${cityWeathers2.list[i].coord.lat} , ${cityWeathers2.list[i].coord.lon}</li>
</ul>
</div>`
// console.log(result2)
document.querySelector("#weathers").innerHTML += result2;
}
}
}
xhr2.send();
}
function loadWeather() {
// console.log(city);
let xhr = new XMLHttpRequest();
const city = document.getElementById("city").value;
const base_path =
"http://api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=XXXXXXXXXXXXXXXXXXXXXXX";
xhr.open("GET", base_path, true);
xhr.onload = function () {
// const city = document.getElementById("city").value;
if (this.status == 200) {
let cityWeathers;
try {
cityWeathers = JSON.parse(this.responseText);
} catch (e) {
// JSON not valid, show error message
}
const result =
`<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">${cityWeathers.name}</h5>
<p class="card-text">Here are some weather details for your City</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Weather: ${cityWeathers.weather[0].main} <img class="card-img-top weather-icon" src="${getIconURL(cityWeathers.weather[0].icon)}" alt="Card image cap"></li>
<li class="list-group-item">Temperature: ${convertKtoF(cityWeathers.main.temp) }° </li>
<li class="list-group-item">Wind Speed: ${convertMPStoMPH(cityWeathers.wind.speed) } </li>
<li class="list-group-item">Geo Location: ${cityWeathers.coord.lat} , ${cityWeathers.coord.lon}</li>
</ul>
</div>`;
document.getElementById("weather").innerHTML = result;
}
}
xhr.send();
}
// Convert from Kelvins to Fahrenheit
function convertKtoF(kelvin) {
return Math.round((kelvin - 273.15) * 1.8);
}
// Convert from Meters Per Second to Miles Per Hour
function convertMPStoMPH(mps) {
return (Math.round(10 * mps * 2.2369362920544) / 10) + " mph";
}
// Weather icon
function getIconURL(icon) {
return "https://openweathermap.org/img/w/" + icon + ".png";
}
Any guidance or suggestions would be greatly appreciated!
I can't speak to the accuracy of the request (per comments), but the problem is xhr2.send(); is within the body of your xhr2.onload function.
For multiple cities, you may need to use city Ids, see https://openweathermap.org/current#severalid. The docs don't seem to mention multiple cities by name as you are attempting to do.

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

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

Handlebars.js and google spreadsheet show/hide content

I am trying to get my content brought into handlebars from my google spreadsheets to be in tags that I can show/hide. When you click on the link it shows one panel of content and hides another panel of content. I have the handlebars bringing the content in from the two google spreadsheets but when I add try to do the hide/show panels it does not work. I had the hide/show panels showing up at one time but with no content from the handlebars in it.
here is my fiddle: http://jsfiddle.net/justawebbie/AcW97/17/
Here is the javascript section:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
// Define spreadsheet URL.
var mySpreadsheet = 'https://docs.google.com/spreadsheet/ccc?key=0AjlSK7_zXoNHdEoyWDYxb3hnZi1xWkl1TVQ0eERBQ2c#gid=0';
var mySpreadsheet2='https://docs.google.com/spreadsheet/ccc?key=0AjlSK7_zXoNHdEpYUEg0VTJ0Rlpzb2RUOVZfLU5oX0E#gid=0'
// Compile the Handlebars template for HR leaders.
var HRTemplate = Handlebars.compile($('#hr-template').html());
var HRTemplate3 = Handlebars.compile($('#hr-template3').html());
// Load top five HR leaders.
$('#hr').sheetrock({
url: mySpreadsheet,
sql: "select A,B,C,N,M,O where B contains 'yes' order by A desc",
headersOff: true,
headers: 2,
rowHandler: HRTemplate
});
$('#hr3').sheetrock({
url: mySpreadsheet2,
sql: "select A,C,D,E order by A desc",
headersOff: true,
headers: 2,
rowHandler: HRTemplate3
});
Here the HTML section:
<ul>
<li>Certificates</li>
<li>Minors</li>
</ul>
<div id="sec1" style="background-color:pink;">
<div id="hr" class="table">
<script id="hr-template" type="text/x-handlebars-template">
<div id='table-row'>
<div id='first-cell'><a href='{{cells.N}}' class='left-link'>{{cells.A}}</a></div>
<div id='second-cell'><a href='{{cells.O}}' class='right-link'>{{cells.M}}</a></div>
</script>
</div>
</div>
<div id="sec2" style="background-color:#eee;">
<div id="hr3" class="table">
<script id="hr-template3" type="text/x-handlebars-template">
<div id='table-row'>
<div id='first-cell'><a href='{{cells.D}}' class='left-link'>{{cells.A}}</a></div>
<div id='second-cell'><a href='{{cells.E}}' class='right-link'>{{cells.C}}</a></div>
</div>
</script>
</div>
</div>
Fiddler appears to be having issues loading the libraries, but it works fine when I build out the page locally. Try this zip file and see if you still have any questions.
http://cris.lc/qtpzm

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