Second AJAX call not functioning - javascript

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.

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

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",
}

Random Quote Machine - Cant tweet quote

I have to tweet a quote that I randomly generated using APIs, but my code isn't working. Here is my code, I added comments trying to make it look clearer. I am a novice in coding so it probably has a terrible sintax.
I manage to get my quote by clicking on the "Get another quote" button, but when i want to tweet my quote, clicking on the "Tweet quote" button it wont work and i get the "Uncaught ReferenceError: data is not defined
at pen.js:10" error.
I dont know what i am doing wrong.
(This is a task for FreeCodeCamp). Thanks to everyone who will answer!
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<h2 class="title">Random Quote Generator</h2>
<h4 class="subtitle">A project for the FreeCodeCamp challenge</h4>
<div class="container-box">
<div class="container-quote">
<p class="quote" id ="quote"></p>
<div class="container-author" id="author">
<p></p>
</div> <!--closing div for container author-->
<div class="row">
<div class="col-md-6">
<button id="tweetQuote" href="https://twitter.com/intent/tweet?text=data.quoteText">Tweet this quote!</button>
</div>
<div class="col-md-6">
<button id="newQuote">Get another quote</button>
</div>
</div> <!--row-->
</div> <!--closing div for container quote-->
</div> <!--closing div for container-->
And now the javascript
//setting html elements to variables
var $newQuote = $('#newQuote');
var $quote = $('#quote');
var $tweetQuote = $('#tweetQuote');
//execute function by clicking on button
$newQuote.click(getQuote);
$tweetQuote.click(tweetIt);
var text = data.quoteText;
var author = data.quoteAuthor;
//when getQuote is called call the APIs and get the quote by executing
getQuoteFromAPI
function getQuote() {
$quote.empty();
getQuoteFromAPI();
};
function getQuoteFromAPI() {
var url='https://api.forismatic.com/api/1.0/?
method=getQuote&format=jsonp&lang=en&jsonp=?';
//when the APIs are completely called execute the parseQuote function
$.getJSON(url).done(parseQuote);
//log the datas on the console and transform them into real html elements
function parseQuote (response) {
console.log(response);
document.getElementById('quote').innerHTML = response.quoteText;
document.getElementById('author').innerHTML = response.quoteAuthor;
};
};
function tweetIt() {
var url='https://api.forismatic.com/api/1.0/?
method=getQuote&format=jsonp&lang=en&jsonp=?';
$('#tweetQuote').attr('href', 'https://twitter.com/intent/tweet?text=' + text + '-' + author);
};

Creating a dependant picklist in Javascript survey monkey api

I'm using the survey monkey PHP API to retrieve a list of surveys in the account. Passing in a $params variable, I can retrieve the survey ID and the survey name. Using the response, I am building two separate picklists as shown below:
function build_picklist($survey, $name) {
global $workbooks;
$picklist = "<select name=\"{$name}\">";
$picklist. = "<option value=\"\" selected=\"selected\">Select...</option>";
foreach($survey['data']['surveys'] as & $entry) {
if ($name == 'survey_list') {
$entry = $entry['title'];
} else {
$entry = $entry['survey_id'];
}
$label = htmlentities($entry);
$picklist. = "<option value=\"{$entry}\">{$label}</option>";
}
$picklist. = "</select>";
$workbooks - > log('Picklist HTML', $picklist);
return $picklist;
}
This works nicely and my form displays a list of surveys on the account and another list of the id's for those surveys. Using the code below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#integrate_button").click(function(){
$(this).val("Integrating...")
});
});
</script>
</head>
<link rel="stylesheet" type="text/css" href="https://secure.workbooks.com/resources/=UzN4IDN/survey_monkey.css">
<title>Integrate with Survey Monkey</title>
<body>
<div id="container" align="center">
<div id="header">
<img src="https://secure.workbooks.com/resources/=UzN4IDN/sm_logo.jpg" height="100" width="200"/>
</div>
<div id="nav">
<p>Below is a list of the Surveys on your account. Pick one to integrate with.</p>
</div>
<div id="section1">
<form method="POST" action="https://secure.workbooks.com/process/=gTOwIjN/Survey_Monkey" id="pg2_form">
<p>Which Survey would you like to integrate Workbooks with?<p>
<p>{$survey_picklist}</p>
<p>Survey ID: <p>
<p>{$survey_id}</p>
</form>
</div>
<div id="section2">
<p><input type="submit" name="integrate" id="integrate_button" form="pg2_form" value="Integrate with Survey Monkey"/></p>
</div>
</div>
</body>
</html>
What I'd like to do is link the two together so when I select an option in the survey name field, it shows the corresponding ID for that survey in the other picklist.
My guess is I'd need to use Jquery/JS to achieve this but I can't seem to find any useful examples on the internet.
I'm new to Jquery/JS and don't really know how to use it that much, things I've done in the past have worked by pure fluke! Please be nice! :)

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