Javascript files not loading in HTML page - javascript

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);

Related

Change Font Color of Search Value Based on JSON Key

I was doing a javascript exercise and wanted to add extra functionality onto it for practice. What I want to do is change the font color of the gem("Page" value in JSON file) depending on a certain value in the json file.
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="https://kit.fontawesome.com/4b3dad3b33.js" crossorigin="anonymous"></script>
<title>Messing With Gems (JSON)</title>
</head>
<body>
<div class="containter mt-5">
<div class="row">
<div class="col-md-6 m-auto">
<h3 class="text-center mb-3">
<i class="fas fa-gem"> Gem Look Up</i>
</h3>
<div class="form-group">
<input type="text" id="search" class="form-control form-control-lg"
placeholder="Type gem/skill name..." />
<div id="match-list"></div>
</div>
</div>
</div>
</div>
<script src="js/main.js"></script>
</body>
</html>
Javascript :
const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
// Search gems.json and filter it
const searchGems = async searchText => {
const res = await fetch('../data/gemz.json');
const gems = await res.json();
// Get Matches to current text input
let matches = gems.filter(gem => {
const regex = new RegExp(`^${searchText}`, 'gi');
return gem.Page.match(regex);
});
if(searchText.length === 0) {
matches = [];
matchList.innerHTML = '';
}
outputHtml(matches);
};
//Show Results in HTML
const outputHtml = matches => {
if(matches.length > 0) {
const html = matches.map(match => `
<div class="card card-body mb-1">
<h4>${match.Page}</h4> <em>(${match.gemdiscription})</em> <span class="text-primary">
${match.gemtags}</span>
</div>
`).join('');
matchList.innerHTML = html;
}
};
search.addEventListener('input', () => searchGems(search.value));
JSON Example ( For example if the "primaryattribute" key has the value of "intelligence" I want the key "Page" value to be displayed in blue on the website when you search for a gem ) I would like to do this with pure javascript to better understand how this is done.
{
"Page": "Frostbite",
"gemdiscription": "Curses all targets in an area,
making them less resistant to cold damage and giving them a chance to be frozen by cold damage.",
"gemtags": [
"Spell",
"AoE",
"Duration",
"Curse",
"Cold"
],
"primaryattribute": "intelligence",
}

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.

angular reset checkbox after ng-change

exploring Angular, I built a simple to-do list.
My issue is that when I use the checkbox to delete an item, say the very last one, the item is deleted but the checkbox above it becomes "checked." I just want to be able to delete the item via the checkbox and all the other checkboxes will remain unchecked. I can't figure the bug here. Dimly, I was thinking I needed to reset the "checked" variable, but that wasn't working.
angular.module('ToDo', [])
.controller('ToDoController', function ($scope, ToDoService) {
$scope.items = ToDoService.items;
$scope.checked = false;
$scope.add = function() {
ToDoService.add($scope.todo);
};
$scope.deleteItem = function() {
ToDoService.deleteItem();
};
$scope.remove = function(idx) {
this.items.splice(idx, 1);
console.log("test inside remove");
return this.items;
};
})
.factory('ToDoService', function () {
return {
items: [],
add: function(todo) {
this.items.push({todo: todo, time: new Date()});
},
deleteItem: function(idx) {
this.items.splice(idx, 1);
console.log("test inside deleteItem");
}
};
});
<html ng-app='ToDo'>
<head>
<title>My Angular To-Do App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src='app.js'></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="app.css">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">My Angular To-Do App</a>
</div>
</div>
</nav>
<div class="container todos" ng-controller='ToDoController'>
<div class="starter-template">
<h1>My To-Do's</h1>
<div class="alert alert-info" role="alert" ng-show="!items.length">
No to-do items have been added yet.
</div>
<ul>
<li ng-repeat='item in items'>{{item.todo}} - {{item.time}} <a class="btn" ng-click="remove()">Delete</a>
<input type="checkbox" ng-model="checked" ng-change="deleteItem(checked)" >
</li>
</ul>
<form class="form-inline">
<input type='text' ng-model='todo' class="form-control" />
<button ng-click='add()' class="btn btn-default">Add</button>
</form>
</div>
</div>
</body>
</html>
You have complicated your app, using factory is unnecessary here. Another thing - your ng-repeat function didn't set id's of added todos - you were deleting always the first element every time you clicked on delete or on checkbox.
ng-repeat='(id, item) in items'
Lastly - I've added a new feature. With every submit of the todo, the todo input gets cleared.
$scope.todo = null;
Codepen
There are multiple bugs in your application. In your situation, you are calling ToDoService.deleteItem without any parameters when your checkbox change boolean state. So, basically you are doing a this.items.splice(undefined, 1); which removes the first element (indeed what happens in your codepen).
You should change the signature of your deleteItem methods in your service and controller to take the name of the todo. Then, you only have to search it and remove it from the list.
.factory('ToDoService', function() {
return {
....
deleteItem: function(itemStr) {
delete this.items[this.items.findIndexOf(function(item) {
return item ==== itemStr;
})];
},
}
})
then in your template you should call remove with the current todo
ng-change="remove(item.todo)"
Using Kind User answer is even simpler, because you have the direct index of your component,
.factory('ToDoService', function() {
return {
....
deleteItem: function(idx) {
delete this.items[idx];
},
}
})

Google Custom Search - don't want trunated title

I am trying to do a simple Google Search where I just get back the titles linked to the pages. I have bought the business search and I have everything working (see code below) - I just want to get the full title of the page, not the truncated title. Can anyone help me?
In my head I have:
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
// Load the Search API
google.load('search', '1');
// Set a callback to load the Custom Search Element when you page loads
google.setOnLoadCallback(
function(){
var customSearchControl = new google.search.CustomSearchControl('011927268382499158334:cuvurabmo-o');
// Use "mysite_" as a unique ID to override the default rendering.
google.search.Csedr.addOverride("mysite_");
// Draw the Custom Search Control in the div named "CSE"
customSearchControl.draw('cse');
},
true);
</script>
In the body I have:
<div style="display:none">
<!-- Return the unescaped result URL.-->
<div id="mysite_webResult" >
<div class="gs-webResult gs-result"
data-vars="{longUrl:function() {
var i = unescapedUrl.indexOf(visibleUrl);
return i < 1 ? visibleUrl : unescapedUrl.substring(i);}}">
<!-- Build the result data structure.-->
<table width="50%" cellpadding="0" cellspacing="0" >
<tr>
<td valign="top">
<!-- Append results within the table cell.-->
<div class="gs-title">
<a class="gs-title" style="color:#990000;font-family:'Times New Roman',serif;font-size:8.0pt;font-decoration:underline;" data-attr="{href:unescapedUrl,target:target}"
data-body="html(title)"></a>
</div>
<!-- Render results.-->
<div data-if="Vars.richSnippet && Vars.richSnippet.action" class="gs-actions"
data-body="render('action',richSnippet,{url:unescapedUrl,target:target})"></div>
</td>
</tr>
</table>
</div>
</div>
<!-- Div container for the searcher.-->
<div id="cse"></div>

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.

Categories

Resources