Unable to load API Function on page load - Javascript - javascript

I am trying to fetch information from TheMovieDB.org using API, I made a simple code to do that, but it works when I add click event to a button/hyperlink, then it displays all the NowPlayingMovies. I want the webpage should display now playing movies itself without any need to click on a button.
I tried to use the window.onload function and put the whole code in one function and remove the need to click on the hyperlink but I am unable to do it and code does not work and shows various errors. Can someone please help me fix it?
window.onload = function updateLatestMovies() {
const xhr = new XMLHttpRequest();
const nowPlayingButton = document.querySelector("#nowPlayingButton");
const endPoint = `https://api.themoviedb.org/3/movie/now_playing?api_key=6a879a78d6083b8f3ba308233e0de85b&language=en-US&page=1`;
xhr.open("GET", endPoint);
xhr.send();
xhr.addEventListener("readystatechange", updateLatestMovies);
const nowPlaying = document.querySelector("#nowPlaying");
if (xhr.readyState == 4) {
const response = JSON.parse(xhr.responseText);
const nowPlayingOutput = document.querySelector("#nowPlaying");
let nowPlayingA = response.results;
let output = "";
for (let i = 0; i < 15; i++) {
output += `
<div id="card">
<a onclick="movieSelected('${nowPlayingA[i].id}')" href="#"><img src="http://image.tmdb.org/t/p/w400/${nowPlayingA[i].poster_path}"></a>
<div class="cardContent">
<a onclick="movieSelected('${nowPlayingA[i].id}')" href="#"><h2>${nowPlayingA[i].title}</h2></a>
<p id="p_rating"><strong>Rating:</strong> <span>${nowPlayingA[i].vote_average} / 10 </span> </p>
<p><strong>Release date:</strong> <span>${nowPlayingA[i].release_date} </span></p>
</div>
</div>`;
}
nowPlayingOutput.innerHTML = output;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Movies Database</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
See what's on Cinema!
<div id="nowPlaying">
</div>
</body>
</html>
And I got the following error:
Uncaught TypeError: Cannot read property 'addEventListener' of null at movie.js:4

Related

I am not sure I can access the second html file using one js file, html element is showing as null when it is a button

I have 2 html files connected to one js file. When I try to access a html element in the second html file using js it doesn't work saying that is is null. I did
let elementname = document.getElementById("element") for a element in the second html page then
console.log(elementname) and it says it is null. When I do it for a element in the first html page it says HTMLButtonElement {}
Here is the html for the first Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Not Quuuuiiiizzzz</h1>
<h2>Join a quiz</h2>
<!--Buttons -->
<div style="text-align: center;">
<button id="btnforquiz1" onclick="gotoquiz()"></button>
<button id="btnforquiz2" onclick="gotoquiz1()"></button>
<button id="btnforquiz3" onclick="gotoquiz2()"></button>
</div>
<h2 id="h2">Create a Quuuuiiiizzzz</h2>
<script src="script.js"></script>
</body>
</html>
For the second page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="quizLoad()">
<h1 id="question">Hello</h1>
<button id="answer1"></button>
<button id="answer2"></button>
<button id="answer3"></button>
<button id="answer4"></button>
<script src="script.js"></script>
</body>
</html>
And Finally for the js file :
//setting global variables
let btn1 = document.getElementById("btnforquiz1") //getting button with id of btnforquiz1 repeat below
correct = 0
let btn2 = document.getElementById("btnforquiz2")
let btn3 = document.getElementById("btnforquiz3")
let question = document.getElementById("question")
let answer1 = document.getElementById("answer1")
let answer2 = document.getElementById("answer2")
let answer3 = document.getElementById("answer3")
let answer4 = document.getElementById("answer4")
quizNameRel = -1;
cosnole.log(question)
console.log(answer1)
//Quiz Data
Quiz_1 = {
"What is the capital of buffalo":["Idk", "Yes", "No",0],
"What is the smell of poop": ["Stinky"]
};
Quiz_2 = [
"What is wrong with you"
];
Quiz_3 = [
"What is wrong with you #2"
]
let quiz = {
name: ["History Test", "Math Practice", "ELA Practice"],
mappingtoans: [0,1,2],
QA: [Quiz_1, Quiz_2, Quiz_3]
}
//quiz data
//when body loades run showQuizzs function
document.body.onload = showQuizzs()
function showQuizzs() {
//loops throo the vals seeting the text for the btns
for (let i = 0; i < quiz.name.length; i++) {
btn1.textContent = quiz.name[i-2]
btn2.textContent = quiz.name[i-1]
btn3.textContent = quiz.name[i]
}
}
//leads to the showQuizzs
function gotoquiz() {
location.href = "quiz.html"
quizNameRel = quiz.name[0]//I was trying to create a relation so we could knoe which quiz they wnt to do
startQuiz()
}
function gotoquiz1() {
location.href = "quiz.html"
quizNameRel = quiz.name[1]
startQuiz()
}
function gotoquiz2() {
location.href = "quiz.html";
quizNameRel = quiz.name[2];
startQuiz();
}
function answerselect(elements){
whichone = Number(elements.id.slice(-2,-1))
if(Quiz_1[whichone]==Quiz_1[-1]){
correct+=1;
NextQuestion();
}else{
wrong+=1;
}
}
//gets the keys and puts it into an array
function getkeys(dictionary){
tempdict = [];
for(i in dictionary){
tempdict.push(i);
}
return tempdict;
}
function setQuestion() {
let tempdict = getkeys(Quiz_1)
console.log(tempdict, getkeys(Quiz_1));
//question.innerHTML = tempdict;
}
// startQuiz
function startQuiz() {
switch (quizNameRel){
case quiz.name[0]:
//case here
setQuestion()
break
case quiz.name[1]:
//case here
break
case quiz.name[2]:
//case here
break
}
}
//TO DO:
// Set the question
// Set the answer
// Check if correct button
This is happening because at a time you have rendered only one html file. For example if you render index1.html(first file) then your js will look for rendered element from first file only but here index2.html(second file) is not rendered so your js script is unable to find elements of that file that's the reason it shows null.
If you try to render now index2.html rather than index1.html then you will find now elements from index2.html are detected by js script but elements from index1.html are null now.

How to program a button to change stylesheets with javascript

Please note that I am not using classes. I haven't found an answer for this SPECIFIC question.
Using javascript, how can I program a button to change the stylesheet each time the button is clicked?
I've tried different if, else if and else, but when I try them, it breaks the code (ie, it will change the color to blue if red, but not back again).
It works with 2 buttons, but getting it to change each time a single button is clicked seems to be eluding me. I got feed up and programmed a second button to change it back.
This works for 2 buttons:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
<style>
</style>
</head>
<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>
<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"}
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"}
}
</script>
</body>
I would like to be able to get rid of the second button and second function and have it all with one button.
EDIT...
I tried this, and it failed.
function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"};
else {document.getElementById("um").href = "stylesheet1.css"}
}
Make sure you're using == instead of = for your comparisons!
if (document.getElementById("um").href == "stylesheet1.css")
etc
Try this:
<button id="x" onclick="myFunction()">Change</button>
<script>
function myFunction() {
var link = document.getElementById("um");
var segments = link.href.split('/');
var currentStyle = segments[segments.length - 1];
var style = (currentStyle == 'stylesheet1.css') ? 'stylesheet2'
: 'stylesheet1';
document.getElementById("um").href = style + ".css"
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
</head>
<body>
<p>booga</p>
<button onclick="myFunction('um','stylesheet1.css', 'stylesheet2.css')">swap</button>
<script>
function myFunction(id,a,b) {
var el = document.getElementById(id);
var hrefStr;
if(~el.href.indexOf(a)) {
hrefStr = el.href.replace(a, b);
el.href = hrefStr;
} else {
hrefStr = el.href.replace(b, a);
el.href = hrefStr;
}
}
</script>
</body>
</html>

Code is not getting inside the $.getJson method because it's getting a 404

Cannot figure out how to actually fix this issue. I have a print line to the console before and after the getJson method and only getting the before.
Here is the error I'm getting on the console:
I have already messed with the path a lot and that doesn't seem to be the issue and I have verified that my JSON is accurate. Here is my JavaScript code
$(document).ready(function () {
var myList;
console.log("here");
$.getJSON('/vegetables.json').done(function (data) {
console.log("also here");
myList = data;
//console.log(myList['vegetables'][0].name);
var uList = document.getElementById("items");
for (i = 0; i < myList['vegetables'].length; i++) {
var div = document.createElement('div');
div.setAttribute('class', 'col-sm-3 vegetables');
var name = document.createElement('h3');
name.innerHTML = myList['vegetables'][i].name;
div.appendChild(name);
var description = document.createElement('p');
description.innerHTML = myList['vegetables'][i].description;
div.appendChild(description);
var price = document.createElement('p');
price.innerHTML = myList['vegetables'][i].price;
div.appendChild(price);
var addToCart = document.createElement('button');
addToCart.setAttribute('value', i);
addToCart.setAttribute('class', 'btn btn-primary');
addToCart.innerHTML = "Add to Cart <img src='glyphicons-203-shopping-cart.png' />";
addToCart.setAttribute('onClick', 'carrot(this)');
div.appendChild(addToCart);
/*<div class="col-sm-3 vegetables" >
<h3 id="div1Name"></h3>
<p id="div1Description">Carrots are orange </p>
<p id="div1Price"></p>
<button onclick="carrot(this)" type="button" class="btn btn-primary" />Add to Cart <img src="glyphicons-203-shopping-cart.png" />
</div>*/
//li.appendChild(panel);
uList.appendChild(div);
}
});
});
Head tags for the jQuery
<head>
<title>Vegetable</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Let me know if anything else will help.
it is searching for the file on your server address, your_server_addr/vegetables.json (EX localhost:8080/vegetables.json) and file is not there on this location.

Correct way to append data into existing data table using ajax

Introduction
I am working with the functions where user search donor organizations by name.
Data loads in DataTable, paging enabled and works fine for the initial data load.
(Data load with initial call from jquery is about 100 records)
Lately, i have tried to implement the ajax method, which is suppose to load "next 100 records" and append to the existing records(now record reaches at 200 aprox).
Problem
Record loading on ajax call is loaded into datatable but displays this recent record on current page(no paging applied on it).
When user change the page to navigate between records, this recent record disappear.
I am just manipulating DOM elements, i think i have to pass it to datatable, yes?
Complete Code(just copy and paste whole code to test,cdn libs used)
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<title>Demo : Test</title>
<!-- Meta -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<form>
<input type="text" id="searchParam" name="searchParm" placeholder="enter search param">
<br>
<input type="submit" value="Submit" onclick="searchDonors(document.getElementById('searchParam').value); return false;">
</form>
<br />
</div>
<div class="col-md-9">
<div id="demoApim"><table id="demoApi"><thead><tr><td>Organization Name</td><td>Address</td></tr></thead><tbody id="tBody"></tbody></table></div>
</div>
<div class="col-md-3" id="searchBtn"><input type="submit" value="Load Next 100 Records" onclick="loadNext(); return false;"></div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
var count;
$('#searchBtn').hide();
$(document).ready(function () { $('table').hide();});
function searchDonors(searchParam) {
window.searchDonorsParam = searchParam;
count = 100;
var request = new XMLHttpRequest();
request.open("GET", "http://graphapi.firstgiving.com/v1/list/organization?q=organization_name:" + searchParam + "*%20AND%20country:US&&page_size=100&page=1", false);
request.send();
var xml = request.responseXML;
//$.each(xml, function (key, val) {
var oName = xml.getElementsByTagName("organization_name");
//console.log(oName);
var oAddress = xml.getElementsByTagName("address_line_1");
var counts = xml.getElementsByTagName("organization_name").length;
for (var i = 1; i < counts; i++) {
var html = [];
html.push('<tr><td>', oName[i].innerHTML)
html.push('</td><td>', oAddress[i].innerHTML)
html.push('</td></tr>')
$("#tBody").append(html.join(''));
}
$('#demoApi').DataTable();
$('table').show();
$('#searchBtn').show();
//});
//console.log(oName);
//console.log(oAddress);
}
function loadNext()
{
if (count = 100)
{
$.ajax({
url: "http://graphapi.firstgiving.com/v1/list/organization?q=organization_name:" + searchDonorsParam + "*%20AND%20country:US&&page_size=100&page=2",
method: "GET",
dataType: "xml",
success: function (xml) {
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
console.log(xml.getElementsByTagName("organization_name"));
var oNameMore = xml.getElementsByTagName("organization_name");
var oAddressMore = xml.getElementsByTagName("address_line_1");
var countsNew = xml.getElementsByTagName("organization_name").length;
var html;
for (var i = 1; i < countsNew; i++) {
html = [];
html.push('<tr><td>', oNameMore[i].innerHTML)
html.push('</td><td>', oAddressMore[i].innerHTML)
html.push('</td></tr>')
$("#tBody").append(html.join(''));
}
},
error: function () {
console.log("call failled");
}
});
}
}
</script>
</body>
</html>
If someone have idea about that problem please let me know, any kind of help or reference will be appreciated.
"I think i have to pass it to datatable, yes?". Yes. The correct way is to go through the API. Without using the API, dataTables cannot be aware of whatever changes you have made to the underlying <table> and therefore your recent records disappear :
var table; //outside your function scopes
in searchDonors() :
table = $('#demoApi').DataTable();
in loadNext() use row.add() instead of injecting markup to <tbody> :
for (var i = 1; i < countsNew; i++) {
table.row.add([oNameMore[i].innerHTML, oAddressMore[i].innerHTML]);
}
table.draw();
yes ofc modify DOM its not enought for datatables, you need to use datatables function to access data, use this:
initialize the table:
var myTable = $('#demoApi').DataTable();
then
myTable.row.add( [oNameMore[i].innerHTML,oAddressMore[i].innerHTML] );
all the data are stored inside datables settings object,
updating the DOM don't change the current table settings so you will
lose you change after any table redraw ( search, change page, ecc.. )

Unable to call a Javascript class from HTML

Please have a look at the below code
TTSScript.js
function TTS()
{
var msg = new SpeechSynthesisUtterance("yohan");
var voices = window.speechSynthesis.getVoices();
this.speakText = function()
{
window.speechSynthesis.speak(msg);
}
}
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/scripts/TTSScript.js"></script>
<script>
function speak()
{
var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);
}
function speak2()
{
var TTS = new TTS();
TTS.speakText();
}
</script>
</head>
<body>
<div><button onclick="speak2()">Click me</button></div>
</body>
</html>
Unfortunatly when I click on the button in the html page, what I get is an error. It is below.
Uncaught TypeError: undefined is not a function (13:42:13:817 | error, javascript)
at speak2 (public_html/index.html:23:26)
at onclick (public_html/index.html:31:126)
I am not much familiar with JavaScript, can you please let me know why I am getting this error and how to fix it?
After declaring a function, its name becomes a (locally) preserved word. It means that creating a variable with the same name might cause some problems.
I took your code and changed
var TTS = new TTS();
TTS.speakText();
Into
var tts = new TTS();
tts.speakText();
And the error disappeared.
I solved your problem.. :
don't use all capital names as variables
var tts = new TTS();
tts.speakText();
correct speak call is in the fiddle
http://jsfiddle.net/bpprwfxa/4/
var msg = new SpeechSynthesisUtterance('Yohan');
window.speechSynthesis.speak(msg);

Categories