getJSON function not triggering - javascript

I am trying to implement a search functionality using API's and JSON data, but for some reason the getJSON function just doesn't seem to work. There are no errors, the first 2 console logs work in both functions but the one inside the getJSON function does not return anything. The url is valid as the same thing happens even if I use just a hard-coded url without the getElementById functionality. I have been trying to get the code to work for the last 2 days but I just have no idea what the problem is. I would appreciate any feedback.
<!DOCTYPE html>
<html>
<head>
<title>World News</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/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
body {
background-color: lightgrey;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">World News</a>
</div>
<form class="navbar-form navbar-right" action="">
<div class="input-group">
<input id="searchBar" type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button onclick="getText(); getJSON();" id="search_btn" class="btn btn-default" type="submit" href="#search">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
</div>
</nav>
<div class="container-fluid text-center">
<div class="row content tab-content">
<div id="home" class="col-sm-8 text-left tab-pane fade in active">
<h1 id="homeH0">Welcome to World News</h1>
<p id="homeP0">Example of the welcoming text for the front of the page</p>
<h4 id="h0"></h4>
<p id="p0"></p>
<h4 id="h1"></h4>
<p id="p1"></p>
<h4 id="h2"></h4>
<p id="p2"></p>
<h4 id="h3"></h4>
<p id="p3"></p>
<h4 id="h4"></h4>
<p id="p4"></p>
</div>
</div>
</div>
<script type="text/javascript">
var urlSer;
function getText() {
urlSer = 'https://newsapi.org/v2/everything?' +
'q=' + document.getElementById("searchBar").value + '&' +
'SortBy=popularity&' +
'apiKey=459a144a981941ffa850e2b8c06c5b5f';
console.log(urlSer);
};
function getJSON() {
console.log(urlSer);
$.getJSON(urlSer, function(json) {
console.log(json);
for (i = 0; i <= 4; i++) {
document.getElementById('h' + i).innerHTML = json.articles['' + i].title;
document.getElementById('p' + i).innerHTML = json.articles['' + i].description;
}
});
};
</script>
</body>
</html>

Change your button from type="submit" to type="button" to prevent the form from submitting using browser default process
Right now your page is probably reloading due to the form submit

Related

Clear/reset the content of a div using a button

I am developing a simple game (similar to Blockly and Scratch) that involves drag-and-drop. After dragging the buttons to a target container, I want to be able to clear the content of that container by pressing a Reset button. I have tried to implement it (which is demonstrated in the code below) but to no avail.
Here are the relevant codes:
<!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, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Play Maze - Zoom Zoom</title>
<script src="{{ url_for('static',filename='vendor/jquery/jquery.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/sb-admin-2.min.js') }}"></script>
</head>
<body id="page-top">
<div id="wrapper">
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordion_sidebar">
<!-- Commands -->
<a class="sidebar-brand d-flex align-items-center justify-content-center">
<div class="sidebar-brand-icon rotate-n-15"><i class="fas fa-laugh-wink"></i></div>
<div class="sidebar-brand-text mx-3">Commands</div>
</a>
<div class="commands">
<div class="draggable">
<input type="button" class="btn-forward" id="forward" value="Forward" draggable="true"></button>
</div>
<div class="draggable">
<input type="button" class="btn-backward" id="backward" value="Backward" draggable="true"></button>
</div>
<div class="draggable">
<input type="button" class="btn-right" id="right" value="Right" draggable="true"></button>
</div>
<div class="draggable">
<input type="button" class="btn-left" id="left" value="Left" draggable="true"></button>
</div>
<div class="draggable">
<input type="button" class="btn-repeat" id="repeat" value="Repeat" draggable="true"></button>
</div>
</div>
</ul>
<!-- Begin Page Content -->
<div class="container-fluid">
<div class="row">
<div class="col-xl-12 col-lg-12">
<div class="card shadow mb-4">
<div class="card-body">
<div class="row">
<div class="col">
<div class="container" id="commands"></div>
<button id="reset" class="btn btn-lg btn-primary" value="Reset"></button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" \
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" \
crossorigin="anonymous" referrerpolicy="no-referrer">
</script>
<script type="text/javascript">
$(document).ready(function()
{
$("button").click(function()
{
$("#commands").empty();
});
});
</script>
</html>
You can make divs' appear or disappear using vanilla javascript only.
A simple example below:
<div id="container">This is Div's content</div>
<reset id="resetButton" value="Reset">Reset</reset>
<script>
resetButton.addEventListener('click', () => {
container.innerHTML = '';
// Or container.style.display = 'none'; if you want container to disappear without leaving space
// Or container.style.visibility = 'hidden'; if you want container to disappear leaving space
});
</script>
Changed to:
<reset id="reset" class="btn btn-lg btn-primary" value="Reset">Reset</reset>
<script type="text/javascript">
$(document).ready(function()
{
$("reset").click(function()
{
$("#commands").empty();
});
});
</script>

Unable to properly add TR to HTML from JS script

I keep getting an indexing error while trying to add TR tags to my HTML using the innerHTML attribute. This is what the JS script looks like.
var myTbody = document.querySelector(".table");
var button = document.querySelector(".add-stock");
var input = document.querySelector(".stock-input");
button.addEventListener("click", function () {
var td = document.querySelectorAll("td");
var row = myTbody.insertRow(td.length + 1);
var cell_univeral = row.insertCell(td.length - 1);
cell_univeral.innerHTML = input.value;
});
And this is the related html document:
<!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>Technical</title>
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="{{url_for('static', filename='css/technical.css')}}"
/>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">Home</a>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNavAltMarkup"
aria-controls="navbarNavAltMarkup"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active" href="#">Technical</a>
<a class="nav-link" href="#">Alpha-Beta</a>
<a class="nav-link" href="#">Partition</a>
<a class="nav-link disabled">More</a>
</div>
</div>
</div>
</nav>
<div class="container">
<div class="content">
<div class="top-form">
<form action='#' method="post">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"
>Ticker Symbols</label
>
<input
type="text"
class="form-control stock-input"
id="exampleInputEmail1"
aria-describedby="emailHelp"
name="nm"
/>
<div id="symbol" class="form-text">Add stocks one at a time</div>
</div>
<div class="buttons">
<div class="add-button">
<button type="button" class="btn btn-success add-stock">Add</button>
</div>
<div class="submit-button">
<button type="submit" class="btn btn-primary submit-btn">
Submit
</button>
<div class="spinner-border my-spinner hidden" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
</div>
</form>
</div>
<div class="bottom-from">
<table class="table table-hover">
<thead>
<th>Symbol <span class="counter"></span></th>
</thead>
<tbody class="table-body">
</tbody>
</table>
<div class="alert alert-warning" role="alert">
It may take longer for multiple stocks
</div>
</div>
</div>
</div>
<script src="{{url_for('static', filename='script/technical.js')}}"
/></script>
</body>
</html>
Note that for the first two click events i have no problems whatsoever though i get this error when i click again
Uncaught DOMException: Index or size is negative or greater than the allowed amount
It seems like I'm trying to change the innerHTML of an item that is out of range but i honestly don't know what the actual problem is and how to fix it. Thank you for your help

JavaScript Error andDebugging

I'm following a tutorial on how to use OMDb API and create a system that can search for movies, but mine is not working. The tutorial am following is the same with mine and it working but mine is not working, Any help please.This is js the source code:
$(document).ready(() => {
$('#searchForm').on('submit', (e) => {
let searchText = $('#searchText').val();
getMovies(searchText);
e.preventDefault();
});
});
function getMovies(searchText){
//The Open Movie Database
axios.get('http://www.omdbapi.com?s='+searchText);
$.then((response) => {
console.log(response);
let movies = response.data.Search;
let output ='';
$.each(movies, (index, movie) =>{
output += '
<div class="col-md-3">
<div class="well text-center">
<img src="${movie.Poster}">
<h5>${movie.Title}</h5>
<a onclick="movieSelected('${movie.imdbID}')" class="btn btn-primary" href="#">Movie Details</a>
</div>
</div>
';
});
$('#movies').html(output);
})
.catch((err) =>
console.log(err);
});
}
<!DOCTYPE html>
<html>
<head>
<title>Movies</title>
<link rel="stylesheet" href="https://bootswatch.com/4/cyborg/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav class="navbar navbar-default" >
<div class="container">
<div class="navbar-header">
Movie Info
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movie">
<br><input type="submit" value="Search Movies">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Your help is highly appreciated, THANKS in advance
Provided you're either using ES6-level JavaScript, or a transpiler which will handle ES6 syntax and translate it to older JavaScript for you, you need to do this:
output += `
<div class="col-md-3">
<div class="well text-center">
<img src="${movie.Poster}">
<h5>${movie.Title}</h5>
<a onclick="movieSelected('${movie.imdbID}')" class="btn btn-primary" href="#">Movie Details</a>
</div>
</div>
`;
...that is, you must surround the above text and code with backticks, not single quotes.

How to use $ngCookies in angularjs

I've a trouble in cookies. When I use ngCookies in my project, there's something wrong in my div (alert).
enter image description here
And here's my app.js
angular.module('postLogin', [ngCookies])
.controller('PostController', ['$scope', '$http', function($scope, $http) {
this.postForm = function() {
var encodedString = 'username=' +
encodeURIComponent(this.inputData.username) +
'&password=' +
encodeURIComponent(this.inputData.password);
$http({
method: 'POST',
url: 'userauth.php',
data: encodedString,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
//console.log(data);
if ( data.trim() === 'correct') {
window.location.href = 'success.html';
} else {
$scope.errorMsg = "Username and password do not match.";
}
})
}
}]);
And here's my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="robots" content="noindex"/>
<title>angulrjs login page</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" id="main-css"/>
<link href="css/style.css" rel="stylesheet" id="main-css"/>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="angular.min.js"></script>
</head>
<body ng-app="postLogin" ng-controller="PostController as postCtrl">
<div class="container">
<div id="loginbox" class="mainbox col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3">
<div class="row">
<img src="images/logo.jpg" class="imglogo"/>
</div>
<div class="panel panel-default" >
<div class="panel-heading">
<div class="panel-title text-center">Login using username & password</div>
</div>
<div class="panel-body" >
<form name="login" ng-submit="postCtrl.postForm()" class="form-horizontal" method="POST">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" id="inputUsername" class="form-control" required autofocus ng-model="postCtrl.inputData.username"/>
</div>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" id="inputPassword" class="form-control" required ng-model="postCtrl.inputData.password"/>
</div>
<div class="alert alert-danger" ng-show="errorMsg">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
×</button>
<span class="glyphicon glyphicon-hand-right"></span> {{errorMsg}}
</div>
<div class="form-group">
<div class="col-sm-12 controls">
<button type="submit" class="btn btn-primary pull-right" ng-disabled="login.$invalid">
<i class="glyphicon glyphicon-log-in"></i> Log in</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
When I didn't use ngCookies
angular.module('postLogin', [])
It could be run as normally. Please help me, I really want it to throwing username in my login form to next page. I can't use $cookies like session in php. Thanks.
In your module setter (angular.module...) when you inject dependent modules they must be in quotes. In your example there are no quotes surrounding ngCookies. Also, your index.html doesn't appear to reference the angular-cookies.js file which is not part of the base angular.js file.
Check development tools for specific error(F12).

Adding Start/Stop functionality to Auto-Refresh Code

I've been digging thru the archives and haven't found exactly what I am looking for, so since I am blocked and on a deadline, hoping someone here with more experience can help me out.
Overall team was happy with what I gave them but they are asking for start/stop button to pause the auto-refresh when they need to grab details about the ads that serve in the page. I've been hacking at it and know I am close, but can someone help me here?
Here's my code so far:
<!doctype html>
<html>
<head>
<title>Demand Tag Testing- Home</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<style type="text/css">
body {
padding-top: 50px;
padding-bottom: 20px;
}
</style>
<script type="text/javascript" language="javascript">
/** Function to refresh the page at specified interval. **/
function autoRefresh(refreshPeriod) {
setTimeout("window.location.reload();",refreshPeriod);
}
</script>
<script type="text/javascript" language="javascript">
/** Function to stop refreshing the page. **/
function stopRefresh()
{
clearTimeout(refreshPeriod);
window.location.hash = 'stop'
}
/** Function to start refreshing the page if stopped. **/
function autoRefresh(refreshPeriod) {
setTimeout("window.location.reload();",refreshPeriod);
window.location.hash = 'start'
}
</script>
</head>
<body onload="autoRefresh(60000);">
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Tag Tester :: Demand Partners</a>
</div>
<!--/.navbar-collapse -->
</div>
</div>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>Demand Tag Testing</h1>
<p>This is a template for testing the tags we get from Demand Partners. It includes scripts that auto-refresh the page every 60 seconds and keeps track of the number of page views for you. You can also manually refresh from cache or the server using the buttons below.</p>
<ul>
<li>There are three ad slots below, load 1 tag per slot.</li>
<li>Allow test to run until pageview counter reaches 500</li>
<li>The pageview counter is PER SESSION, so if you close your browser, you will lose the count</li>
</ul>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class="col-lg-6">
<h2>Ad Slot #1</h2>
<p>Paste Ad Tags Here</p>
</div>
<div class="col-lg-3">
<h2>Ad Slot #2</h2>
<p>Paste Tags Here</p>
</div>
<div class="col-lg-3">
<h2>Ad Slot #3</h2>
<p>Paste Tags Here</p>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<h2>Page Reload Count:</h2>
<script type="text/javascript" language="javascript">
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.write("The page has been reloaded " + sessionStorage.clickcount + " time(s) in this session.");
</script>
<div class="btn-group">
<a class="btn btn-success" onclick="startRefresh()" id="start">Start Refresh</a>
<a class="btn btn-danger" onclick="stopRefresh()" id="stop">Stop Refresh</a>
<p id="console"></p>
</div>
</div>
<div class="col-lg-4">
<h2>Reload Cached Page:</h2>
<a class="btn btn-success" href="javascript:window.location.reload();">Click To Reload From Cache</a>
</div>
<div class="col-lg-4">
<h2>Reload From Server</h2>
<button class="btn btn-success" onclick="window.location.reload(true);">Click To Reload From Server</button>
</div>
</div>
<hr>
<footer>
<p>© Company Name, Inc 2014</p>
</footer>
</div>
<!-- /container -->
</body>
</html>
I just need help linking those start/stop buttons to my refresh code and some output that lets users know when it's toggled, so any help anyone can provide here would be greatly appreciated!
You have few issues there, first of all you don't have start function but two autoRefresh which is a typo I guess .. Second, you need to declare global variable and store the timeout in there. Here is updated code which should work:
<!doctype html>
<html>
<head>
<title>Demand Tag Testing- Home</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<style type="text/css">
body {
padding-top: 50px;
padding-bottom: 20px;
}
</style>
<script type="text/javascript" language="javascript">
var myRefreshTimeout;
/** Function to refresh the page at specified interval. **/
function startRefresh(refreshPeriod) {
myRefreshTimeout = setTimeout("window.location.reload();",refreshPeriod);
}
/** Function to stop refreshing the page. **/
function stopRefresh() {
clearTimeout(myRefreshTimeout);
window.location.hash = 'stop'
}
</script>
</head>
<body onload="startRefresh(60000);">
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Tag Tester :: Demand Partners</a>
</div>
<!--/.navbar-collapse -->
</div>
</div>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>Demand Tag Testing</h1>
<p>This is a template for testing the tags we get from Demand Partners. It includes scripts that auto-refresh the page every 60 seconds and keeps track of the number of page views for you. You can also manually refresh from cache or the server using the buttons below.</p>
<ul>
<li>There are three ad slots below, load 1 tag per slot.</li>
<li>Allow test to run until pageview counter reaches 500</li>
<li>The pageview counter is PER SESSION, so if you close your browser, you will lose the count</li>
</ul>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class="col-lg-6">
<h2>Ad Slot #1</h2>
<p>Paste Ad Tags Here</p>
</div>
<div class="col-lg-3">
<h2>Ad Slot #2</h2>
<p>Paste Tags Here</p>
</div>
<div class="col-lg-3">
<h2>Ad Slot #3</h2>
<p>Paste Tags Here</p>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<h2>Page Reload Count:</h2>
<script type="text/javascript" language="javascript">
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.write("The page has been reloaded " + sessionStorage.clickcount + " time(s) in this session.");
</script>
<div class="btn-group">
<a class="btn btn-success" onclick="startRefresh()" id="start">Start Refresh</a>
<a class="btn btn-danger" onclick="stopRefresh()" id="stop">Stop Refresh</a>
<p id="console"></p>
</div>
</div>
<div class="col-lg-4">
<h2>Reload Cached Page:</h2>
<a class="btn btn-success" href="javascript:window.location.reload();">Click To Reload From Cache</a>
</div>
<div class="col-lg-4">
<h2>Reload From Server</h2>
<button class="btn btn-success" onclick="window.location.reload(true);">Click To Reload From Server</button>
</div>
</div>
<hr>
<footer>
<p>© Company Name, Inc 2014</p>
</footer>
</div>
<!-- /container -->
</body>
</html>

Categories