AJAX Powered Data Driven App - javascript

When I type in an artist and I click the button, I should get a nice list of their songs in a format that is aesthetically pleasing.
My error is:
Nothing is returns whenever I press the button, I don't know why that is.
HTML File
<!DOCTYPE html>
<html>
<head>
<title>Songs</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<script src="ajaxfunctions.js"></script>
</head>
<body>
<div class="container">
<h2>Songs </h2>
<br/>
<p>Try entering an artist to find their songs</p>
<div>
<div id="musicbox" class="control-group">
<label for="songs">artistr</label>
<input type="text" name="songs" id="songs" placeholder="Type an artist to their songs" />
</div>
</div>
<br />
<div>
<button class='btn btn-success btn-large' onclick="Music('songs')">Find Songs</button>
</div>
<br />
<div>
</div>
</div>
</body>
</html>
JS File
function Music(music) {
var yourmusic = document.getElementById(music).value;
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
if (this.readyState === 4) {
if(this.status === 200) {
displayMusic(this.responseText);
} else if (this.status === 404){
displayMusic('{ "songs" : "none" }');
} else {
console.log("We have a problem: " + this.status);
}
} else {
}
};
var url = " https://api.mixcloud.com/discover/funk/";
httpRequest.open("GET", url, true);
httpRequest.send();
}
function displayMusic(data){
var music = JSON.parse(data);
if(music.songs === "none") {
document.getElementById("songs").className = "alert alert-warning";
document.getElementById("songs").innerHTML = "The songs are" + music;
} else {
document.getElementById("songs").className = "alert alert-success";
document.getElementById("songs").innerHTML ="there are no songs for this artist"
}
}

Related

How to change full content using AJAX

I want the whole page content to change when I press the button from the Words.html to SelectNumber.html
This is the Words.html
<html>
<head>
<meta charset="UTF-8">
<title>Number Game</title>
<link rel = "stylesheet" href = "stylesheet.css">
</head>
<body>
<div id = "firstScreen">
<h1 id ="Title" class = "title">
The<br>Number Game
</h1>
<input type = "image" src = "button.png" class = "button1" onclick = "loadScreen">
<h3 class = "start">START</h3>
</div>
</body>
<script src = "Main.js"> </script>
</html>
This is the JS
function loadScreen()
{
var load = new XMLHttpRequest();
load.onreadystatechange = function()
{
document.getElementById("firstScreen").innerHTML = this.responseText;
}
};
load.open("GET", "SelectNumber.html", true);
load.send();
}
function myFunction(load)
{
document.getElementById("firstScreen").innerHTML = load.responseText;
}
And this is the SelectNumber.html
<html>
<head>
<meta charset="UTF-8">
<title>Number Game</title>
<link rel = "stylesheet" href = "stylesheet.css">
</head>
<body>
<div id="Screen2">
<p> Hello World</p>
</div>
<script src = "Main.js"></script>
</body>
</html>
I want the whole content to change from Words.html to NumberSelect.html when I press the input button.
function loadScreen() {
var load = new XMLHttpRequest();
load.onreadystatechange = function() {
document.getElementById("firstScreen").innerHTML = this.responseText;
}
load.open("GET", "select.html", true);
load.send();
}
function myFunction(load) {
document.getElementById("firstScreen").innerHTML = this.responseText;
}
loadScreen();

Cannot read property 'innerHTML' of null error. My script is at the end of the body, why am I still getting this error?

My script is at the end of the body, which has been the basic answer I've seen given when searching for a solution. What am I doing wrong? Do I need to use async/await? I've written almost this exact code before, and its worked.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body id="body">
<h1 id="header">Pokemon</h1>
<div id="main-container">
</div>
<button id="button">Click</button>
<script type="text/javascript" src="ajax.js"></script>
</body>
</html>
JS:
let pokemon = document.querySelectorAll('.poke');
let button = document.getElementById('button');
let container = document.getElementById('main-container');
function loadPokemon() {
const urs = 'https://pokeapi.co/api/v2/pokemon';
let xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
const poke = JSON.parse(xhr.responseText)
container.innerHTML+= `
${poke.results.map(function(pok, index) {
return `
<div class='poke'>
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png">
</img>
${pok.name}
</div>
`
})}
`
}
}
xhr.open('GET', urs, true);
xhr.send();
};
button.addEventListener('click', loadPokemon);
It is working here.. I did not make any changes to your code
let pokemon = document.querySelectorAll('.poke');
let button = document.getElementById('button');
let container = document.getElementById('main-container');
function loadPokemon() {
const urs = 'https://pokeapi.co/api/v2/pokemon';
let xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
const poke = JSON.parse(xhr.responseText)
container.innerHTML+= `
${poke.results.map(function(pok, index) {
return `
<div class='poke'>
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png">
</img>
${pok.name}
</div>
`
})}
`
}
}
xhr.open('GET', urs, true);
xhr.send();
};
button.addEventListener('click', loadPokemon);
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body id="body">
<h1 id="header">Pokemon</h1>
<div id="main-container">
</div>
<button id="button">Click</button>
<script type="text/javascript" src="ajax.js"></script>
</body>
</html>
Your code is working fine. Are you sure you copy and pasted the exact code?

How to get json text into html DOM

I am able to get the data from an external URL JSON but cant put it into the DOM not too sure what I'm doing wrong but here's my code. I suspect that it has something to do with the obj.fruit.json but not too certain
<!DOCTYPE html>
<html>
<head>
<title>Starting Point</title>
<script>
function do_exercise()
{
var x = new XMLHttpRequest();
x.open('GET', 'http://tmaserv.scem.uws.edu.au/fruit.json', true);
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status ==200) {
alert(x.responseText);
obj = JSON.parse(text);
document.getElementById("section1").innerHTML =
obj.fruit.json[2].name + " " +
obj.fruit.json[2].description;
}
}
x.send(null);
}
</script>
</head>
<body>
<nav>
<button onclick="do_exercise();">Click Me</button>
</nav>
<section id = "section1">
<h1>Heading One</h1>
<p>Paragraph One.</p>
</section>
</body>
</html>
cheers
<!DOCTYPE html>
<html>
<head>
<title>Starting Point</title>
<script>
function do_exercise () {
var x = new XMLHttpRequest();
x.open('GET', 'http://tmaserv.scem.uws.edu.au/fruit.json', true);
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status ==200) {
obj = JSON.parse(x.responseText);
document.getElementById("section1").innerHTML =
obj[2].name + " " +
obj[2].description;
}
}
x.send(null);
}
</script>
</head>
<body>
<nav>
<button onclick="do_exercise();">Click Me</button>
</nav>
<section id = "section1">
<h1>Heading One</h1>
<p>Paragraph One.</p>
</section>
</body>
</html>

How to prevent empty input in text input form?

Here is my HTML -
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> My Shopping List</title>
<link rel="stylesheet" type="text/css" href="shoppinglist.css">
<link href='http://fonts.googleapis.com/css?family=Quicksand:300,400|Advent+Pro:300' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="shoppinglist.js"></script>
</head>
<body>
<div class="container">
<p id="shoppinglist"> My Shopping List App</p>
<input type="text" name="user" class="entertext">
<input type="button" value="Enter" class="returnkey">
<br>
<br>
<ol></ol>
</div>
</body>
</html>
Here is my JavaScript -
$(document).ready(function () {
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$("input[type='text']").keyup(function(event) {
if(event.keyCode == 13) {
$("input[type='button']").click();
}
});
$("ol").on("click", "input[type='checkbox']", function() {
$(this).parent().remove();
});
});
How do I create JavaScript for someone whose entering empty? So something to prevent them from empty text input?
You can check if the value of the text input is equal to a blank string:
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
//start new code
if ($.trim(item) === '') {
alert("Please Enter Something!");
return false;
}
//end new code
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$.trim() removes any extra white-space, to make sure the input doesn't just have white-space as a value.
Something like this?
$('.returnkey').on('click', function() {
var string = $.trim($('.entertext').val());
if (string == '') {
alert('Field is empty');
return false;
}
}

GET request into table

I have this next html document, which has to load a table, which is filled with the values I get back from a XMLHttpRequest.
when I try to run the page, it won't give anything like a table back, so if anyone sees what's the problem in this code, please help!!
<!doctype html>
<html class="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Evenementen | Sociale buurt</title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="onzebuurt.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
window.onload = function() {
initialiseListEvenementen();
};
initialiseListEvenementen() {
var BASE_URL = "http://localhost:8080/OnzeBuurt2/resources/";
var events = [];
//load the groups from the back-end
var request = new XMLHttpRequest();
request.open("GET", BASE_URL + "events");
request.onload = function() {
if(request.status === 200) {
events = JSON.parse(request.responseText);
for(var i = 0; i < events.length; i++) {
$("#eventList").append(createListElementForEvent(i));
}
if(events.length > 0) {
$("#eventList").listview('refresh');
} else {
console.log("Error");
}
} else {
console.log("Error loading groups: " + request.status + " - "+ request.statusText);
}
};
request.send(null);
}
function createListElementForEvent(eventIndex) {
var datum = $("<p>").text("Datum: " + events[eventIndex].datum);
var titel = $("<p>").text("Titel: " + events[eventIndex].titel);
var details = $("<p>").text("Details: " + events[eventIndex].details);
var auteur = $("<p>").text("auteur: " + events[eventIndex].auteur.naam);
var latitude = $("<p>").text("Datum: " + events[eventIndex].locatie.latitude);
var longitude = $("<p>").text("Datum: " + events[eventIndex].locatie.longitude);
return $("<li>").append(datum).append(titel).append(details).append(auteur).append(latitude).append(longitude);
}
</script>
</head>
<body class="body2">
<div class="gridContainer clearfix">
<div class="header2">
<center>
Evenementen
</center>
</div>
<ul id="eventList" class="lijst"></ul>
<div id="home2">
<form name="input" action="" method="get">
<img src="home.png" alt="Home" />
</form>
</div>
<div id="terug2">
<form name="input" action="" method="get">
<img id="btnterug" src="vorige.png" alt="Vorige" />
</form>
</div>
</div>
</body>
</html>
after couple of hours of work, I found the solution. Hope i can help some of you:
<!doctype html>
<html class="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Evenementen | Sociale buurt</title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="onzebuurt.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var url = "http://localhost:8080/OnzeBuurt2/resources/events";
var events = [];
$(document).ready(function() {
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if(request.status === 200) {
events = JSON.parse(request.responseText);
for(var i = 0; i < events.length; i++) {
$("#eventList").append(createListElementForEvent(i));
}
if(events.length > 0) {
$("#eventList").listview('refresh');
} else {
console.log("Error");
}
} else {
alert("fout gegaan");
console.log("Error loading groups: " + request.status + " - "+ request.statusText);
}
};
request.send(null);
});
function createListElementForEvent(eventIndex) {
var datum = $("<td>").text(events[eventIndex].datum);
var titel = $("<td>").text(events[eventIndex].titel + " - " + events[eventIndex].details);
var auteur = $("<td>").text(events[eventIndex].auteur.naam);
return $("<tr>").append(datum).append(titel).append(auteur);
}
</script>
</head>
<body class="body2">
<div class="gridContainer clearfix">
<div class="header2">
<center>
Evenementen
</center>
</div>
</div>
<div class="tabelEvents">
<table id="eventList" class="tabel" border="1">
<tr><th>Datum</th><th>Titel</th><th>Auteur</th></tr>
</table>
</div>
<div id="home2">
<form name="input" action="" method="get">
<img src="home.png" alt="Home" />
</form>
</div>
<div id="terug2">
<form name="input" action="" method="get">
<img id="btnterug" src="vorige.png" alt="Vorige" />
</form>
</div>
</body>
</html>

Categories