Overwrite a div using JS and foreach loop / append - javascript

I'm looking to overwrite a div using JS but the issue is that I'm using append so the script keep writing data at the end of the div, I have no idea how to fix that, I tried window.location.reload(true) but, obviously, the data is lost.
Can someone point me to the right direction, actually I'm lost. My goal is to refresh / erase or update the div content, preferably, whiteout reloading the page. Here's a runnable code so you can see the problem. Thanks for you help.
$("#getnews").on("click", function() {
setTimeout(function() {
var path = "https://api.iextrading.com/1.0/stock/"
var stock = document.getElementById('userstock').value
var end = "/news"
var url = path + stock + end
$.getJSON(url, function(data) {
data.forEach(function (article) {
$('#data').append(
$('<h4>').text(article.headline),
$('<div>').text(article.summary),
$('<hr>').text(" "),
);
});
});
},200);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<div class="container">
<p>Search for a stock (E.g: msft, aapl or tsla)</p>
<p><input type="text" id="userstock"></p>
<p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p>
<row id="data"></row>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>

$("#getnews").on("click", function() {
setTimeout(function() {
var path = "https://api.iextrading.com/1.0/stock/"
var stock = document.getElementById('userstock').value
var end = "/news"
var url = path + stock + end
$.getJSON(url, function(data) {
var html = $("<div></div>");
data.forEach(function (article) {
html.append($('<h4>').text(article.headline));
html.append($('<div>').text(article.summary));
html.append($('<hr>').text(" "));
});
$('#data').html(html);
});
},200);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<div class="container">
<p>Search for a stock (E.g: msft, aapl or tsla)</p>
<p><input type="text" id="userstock"></p>
<p><a class="btn btn-dark btn-large text-white" id="getnews">Browse</a></p>
<row id="data"></row>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>

Can't you just set the HTML of the container:
var html = $("<div></div>");
html.append($('<h4>').text(article.headline));
html.append($('<div>').text(article.summary));
html.append($('<hr>').text(" "));
$('#data').html(html);

Related

How to insert buttons in popover

I am trying to insert html attribute buttons into popover in bootstrap5 by JavaScript.
I am trying to make a clear button with this function below:
But button is not showing. Only text inside the popover.
popStr = popStr + "</div> <a href='/shop/checkout'><button class='btn btn-primary' id='checkout'>Check out</button></a> <button class='btn btn-primary' onclick='clearCArt()' id='clearcart'>Clear cart</button>"
console.log(popStr);
document.querySelector('[data-id="popcart"]').setAttribute('data-bs-content', popStr);
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-id="popcart"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl,
{
html: true
})
});
function clearCart() {
cart = JSON.parse(localStorage.getItem('cart'));
for (var item in cart) {
document.getElementById('div' + item).innerHTML = '<button id="' + item + '"class="btn btn-primary cart">Add To Cart</button>'
}
localStorage.clear();
cart = {};
updateCart(cart);
}
You can try using anchor tag instead of a button.
var popover = new bootstrap.Popover(document.querySelector('.my-popover'), {
container: 'body',
placement : 'auto',
html : true,
title : 'Your Selected Items',
content : '<div class="p-1"><ol><li>Item</li><li>Item</li><li>Item</li><ol></br> Check Out Clear Cart</div>'
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<button type="button" class="btn btn-primary my-popover" data-bs-toggle="popover">Click Me</button>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
Update for the buttons to work
Firstly i changed popover content
Old version :
content : '<div class="p-1"><ol><li>Item</li><li>Item</li><li>Item</li><ol></br> Check Out Clear Cart</div>'
New version :
I changed anchor href="#" to href="javascript:void(0)" prevent to redirect another place or page.
content : '<div class="p-1"><ol><li>Item</li><li>Item</li><li>Item</li><ol></br> Check Out Clear Cart</div>'
And then i tested. I can catch buttons (anchor) only when popover shown popover._element returns to popover button.
document.addEventListener("DOMContentLoaded", function(event) {
popover._element.addEventListener('shown.bs.popover', function () {
var btn = document.getElementById('checkOut');
btn.onclick = function() { clearCart() };
})
});
I'm guessing that for security reasons. Bootstrap doesn't let for button. but we can set function as above
Complete snippet
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<button type="button" class="btn btn-primary my-popover" data-bs-toggle="popover">Click Me</button>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
-->
<script>
var popover = new bootstrap.Popover(document.querySelector('.my-popover'), {
container: 'body',
placement : 'auto',
html : true,
title : 'Your Selected Items',
content : '<div class="p-1"><ol><li>Item</li><li>Item</li><li>Item</li><ol></br> Check Out Clear Cart</div>'
})
document.addEventListener("DOMContentLoaded", function(event) {
popover._element.addEventListener('shown.bs.popover', function () {
var btn = document.getElementById('checkOut');
btn.onclick = function() { clearCart() };
})
});
function clearCart(){
console.log('Array cleared');
}
</script>
</body>
</html>

Data not getting pushed to firebase (inconsistent behaviour)

I'm trying to push suspect records in the firebase database, everything is working correctly, but the pushing part doesn't seem to be working. It works very rarely, not every time.
Here is the function:
async function storeSuspectData() {
var name = document.getElementById("name").value;
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
var idnumber = document.getElementById("idnumber").value;
var dob = document.getElementById("dob").value;
var crime = document.getElementById("crime").value;
var hypo = document.getElementById("hypo").value;
var gender;
if (document.getElementById("male").checked) {
gender = 'male';
}
else if (document.getElementById("female").checked) {
gender = 'female';
}
console.log(sessionStorage.getItem("userKey") + ' ' + name + ' ' + height + ' ' + weight + ' ' + idnumber + ' ' + dob + ' ' + gender + ' ' + crime + ' ' + hypo);
console.log('/users/' + sessionStorage.getItem("userKey") + '/suspectList/');
let token = await database.ref('/users/' + sessionStorage.getItem("userKey") + '/suspectList/');
await token.push().set({
name: name,
height: height,
weight: weight,
idnumber: idnumber,
dob: dob,
gender: gender,
crime: crime,
hypo: hypo,
});
alert('Record added successfully');
}
The last alert statement is not getting executed and data is not being pushed
Here is the database
I'm also getting this error on console, but I'm not using document.write() anywhere
BrowserPollConnection.ts:480 [Violation] Avoid using document.write().
The page is getting refreshed when I click the button on which the function is called as the button is a submit button in a form. I get this
Navigated to file:///D:/MyPrograms/CredibilityAnalyzer/front-end/pages/selectSuspect.html?name=afs&crime=0&height=1&weight=1&idnumber=1&dob=2021-01-01&hypo=asdf&gender=none
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Credibility Analyzer</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"
integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<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" type="text/css" href="../style/selectSuspect.css">
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.7.1/firebase-analytics.js"></script>
<script src="../script/form2.js"></script>
</head>
<body onload="fillSuspectList()">
<div class="testbox">
<form>
<div class="banner">
<h1>Credibility Analyzer</h1>
</div>
<div class="btn-block">
<button type="submit" onclick="showInputForm()">Enter new suspect record</button>
<button type="submit" onclick="showSelectSuspect()">Select suspect</button>
</div>
<div class="showInputForm" id="showInputForm" style="display: none;">
<p>Suspect Information</p>
<div class="item">
<label for="name">Name<span>*</span></label>
<input id="name" type="text" name="name" required />
</div>
<div class="btn-block">
<button type="submit" onclick="storeSuspectData()">SUBMIT</button>
</div>
</div>
</form>
</div>
<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>
</body>
</html>
It works very rarely, not every time.
This typically indicates a race condition. In this case I suspect that your storeSuspectData is being called when the user submits a form. If that's the case: the default behavior for a form is to send the data to the server, and then redirect to a different page. So unless your handler function cancels this default behavior, the page will be redirected and this may/will interrupt the write to the database.
The solution for this is to cancel the default behavior of the form by calling e.preventDefault() on the event that triggers it, and returning false from the handler.

Add a Google Sheet list of values to the materialize autocomplete function

I'm trying to create a simple web app that add countries to a google sheet. And use materialize autocompletes to assist the user (which simply autocomplete the country, with no images attached). I saw a couple of examples of the materialize autocomplete, but always with a predefined autocomplete list. This is the html I used:
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete">
<label for="autocomplete-input">Country</label>
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<!-- Compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
google.script.run.withSuccessHandler(tags).getCountry();
function tags(data) {
var availableTags = data;
$('input.autocomplete').autocomplete({
data: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>
And this is my code in google script, the function getCountry works, and returns a list of countries. But I didn't succeed in adding them to the materialize autocomplete function.
function doGet() {
var template = HtmlService.createTemplateFromFile("page");
var html = template.evaluate();
return html;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1_GtmVrdD1Es6zQZna_Mv-Rc3JkIu66-q_knQ8aqcUIc/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
function getCountry(){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
list = list.map(function(r){return r[0]; });
Logger.log(list);
var data = "{";
for (var i = 0; i < list.length; i++) {
data = data + "'" + list[i] + "': null,";
}
data = data.slice(0, -1) + "}";
Logger.log(data);
return data;
}
This is the information on https://materializecss.com/autocomplete.html
// Or with jQuery
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
});
});
Answer:
You can use web polling to update your page with a set interval such that it always retrieves updated data from the Sheet.
Code:
Piggybacking off the answer here, edit your script to include:
function polling(){
setInterval(update, 500);
}
function update(){
google.script.run.withSuccessHandler(tags).getCountry();
}
and make sure that you run the polling() function on load:
<body onload="polling()">
<!-- your body goes here -->
</body>
Full page.html:
<html>
<head>
<meta charset="utf-8">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body onload="polling()">
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete" placeholder="Country">
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<script>
function polling(){
setInterval(update, 500);
}
function update(){
google.script.run.withSuccessHandler(tags).getCountry();
}
google.script.run.withSuccessHandler(tags).getCountry();
function tags(list) {
console.log(list);
var availableTags = list;
$("#autocomplete-input").autocomplete({
source: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>
And leave your code.gs file unchanged.
References:
Stack Overflow - Creating an autocomplete function in Google Script that works with a list of values from the Google Sheet
Stack Overflow - Is it possible to import XML or JSON data from a table within a Word online document into Apps Script website as an HTML table?
Changing the getCountry() function, so it reads the data as an object and not as a string fixed it.
function doGet() {
var template = HtmlService.createTemplateFromFile("page");
var html = template.evaluate();
return html;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1_GtmVrdD1Es6zQZna_Mv-Rc3JkIu66-q_knQ8aqcUIc/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
function getCountry(){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
list = list.map(function(r){return r[0]; });
Logger.log(list);
var data = {};
for (var i = 0; i < list.length; i++) {
data[list[i]] = null;}
return data;
}
And the html stayed the same:
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete">
<label for="autocomplete-input">Country</label>
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<!-- Compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
google.script.run.withSuccessHandler(tags).getCountry();
function tags(data) {
var availableTags = data;
$('input.autocomplete').autocomplete({
data: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>

clicking next page causes my page to slow down exponentially

this is my first time asking a question on Stack Overflow, any help would be greatly appreciated.
I have a website that displays images from the pixabay api. When i click the button, next, the next page of images is shown. The problem is that with each click, the page slows down at an exponential rate. I know this because i added a success console.log after every completion.
This is the image before:
Image Link Here.
and after
Image Link Here
I think the problem has something to do with the .getJSON call and the for loop inside that call, but I havn't been able to figure it out.
This is the Javascript and HTML
/*
Pixabay api key:
*/
$(document).ready(function () {
var searchValue = "rice"
var defaultPage = 1;
returnPhotos(searchValue, defaultPage);
$("#searchForm").on("submit", function (event) {
//obtain value from user input
searchValue = $("#searchText").val();
returnPhotos(searchValue, defaultPage);
//stops form from submitting to a file
event.preventDefault();
});
});
/*
1. Return Photos from pixabey API
*/
function returnPhotos(searchValue, pageNum) {
let key = "8712269-5b0ee0617ceeb0fd2f84487c3";
let startURL = "https://pixabay.com/api/?key=" + key;
let page = "&page=" + pageNum;
let imagesPerPage = "&per_page=" + 22
let addWH = "&min_width&min_height";
let safeSearch = "&safesearch=true";
let endingURL = "&q=" + searchValue + page + addWH + safeSearch + imagesPerPage;
// activate api and get data
$.getJSON(startURL + endingURL, function (data) {
let image = data.hits;
var imageLength = image.length;
arrayLength = image.length;
if (data) {
let output = ""
for (let x = 0; x < arrayLength; x++) {
//imageObject contains information on each image passed through the array
let imageObject = {
// id: image[x].id,
// pageURL: image[x].pageURL,
// tags: image[x].tags,
// previewURL: image[x].previewURL,
// previewWidth: image[x].previewWidth,
// previewHeight: image[x].previewHeight,
// webformatURL: image[x].webformatURL,
// webformatWidth: image[x].webformatWidth,
// webformatHeight: image[x].webformatHeight,
largeImageURL: image[x].largeImageURL,
// fullHDURL: image[x].fullHDURL,
// views: image[x].views,
// user_id: image[x].user_id,
// user: image[x].user,
// userImageURL: image[x].userImageURL
}
// output this template to the website
output += `
<div class="brick">
<img src="${imageObject.largeImageURL}">
</div>
`
}
$(".masonry").imagesLoaded(function () {
localStorage.clear();
$(".masonry").html(output);
});
console.log("success");
} else {
console.log("Didn't work");
}
getPage(searchValue, pageNum, arrayLength);
// console.log(arrayLength);
});
}
/*
2. INCREASE/Decrease PAGE
*/
function getPage(searchValue, defaultPage, max) {
if (defaultPage <= max + 1) {
$("#pagination2").click(function () {
if (defaultPage <= max) {
defaultPage++;
returnPhotos(searchValue, defaultPage);
console.log(1);
}
$(".pageNumber").html("Page " + defaultPage);
console.log("This is the default page:", defaultPage);
});
}
$("#pagination1").click(function () {
if (defaultPage != 1) {
defaultPage--;
returnPhotos(searchValue, defaultPage);
console.log(1);
}
$(".pageNumber").html("Page " + defaultPage);
console.log("This is the default page:", defaultPage);
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv='cache-control' content='no-cache'>
<title>Photo Gallery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="vendors/css/ionicons.min.css">
<link rel="stylesheet" type="text/css" href="vendors/css/animate.min.css">
<link rel="stylesheet" href="resources/css/style.css">
<link href="data:image/x-icon;base64,AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+4z/L/pMLv//j6/f///////v7//6vG8P+lwu//5u76/3ek5/+70fP///////7+/v+wyvH/daLn/9Hg9////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/8PX8///////H2vX/CFnU/4yy6v/W4/j/ClvU/4St6f//////y9z2/xVi1v9QiuD/9Pf9////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f/w9fz/9Pf9/z9+3f9Egd7/8/f9/9bj+P8KW9T/hK3p/+7z+/8ob9n/LXLa//D0/P////////////////////////////////////////////////////////////////////////////////////////////////9UjOH/JGzZ/87e9v+Bqun/CVrU/8zc9v//////1uP4/wpb1P9+qej/ZZfk/xdj1v/J2/X//////////////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/jrPr/zB02/8RX9X/e6bo//X4/f/W4/j/ClvU/2+e5v8faNj/oL/u////////////////////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f/w9fz/+vz+/6zH8P8EVtP/p8Tv/9bj+P8KW9T/cqDm/yRs2f9ek+P/+fv+//////////////////////////////////////////////////////////////////////////////////////////////////////9UjOH/JGzZ//D1/P///////v7//xJf1f9vnuX/1uP4/wpb1P+ErOn/nb3t/wdY1P+cvO3//v7//////////////////////////////////////////////////////////////////////////////////////////////////1SM4f8kbNn/8PX8//7+///J2/X/BFbT/5G17P/W4/j/ClvU/4St6f/5+/7/RoLe/xZi1v/e6fn/////////////////////////////////////////////////////////////////////////////////////////////////VIzh/yRs2f+au+3/RYLe/xdj1v9bkeL/7/T8/9bk+P8MXNX/ha3q///////W4/f/GmXX/0iE3//1+P3///////////////////////////////////////////////////////////////////////////////////////////+70fP/p8Tv/8fZ9f+jwe//xtn1/8nMz/+Ojo7/vcDG/77S8v/f6fn///////7+/v/P3/b/wNT0//T4/f/////////////////////////////////////////////////////////////////////////////////////////////////////////////////39/f/aWlp/9jY2P9ycnL/29vb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////v7+/9LS0v/CwsL/9/f3//r6+v9oaGj/vr6+/2xsbP/f39//7Ozs/729vf/j4+P//v7+//////////////////////////////////////////////////////////////////////////////////////////////////////+7u7v/f39//6CgoP+JiYn//v7+/+Hh4f+pqan/29vb//n5+f9mZmb/qqqq/2xsbP/h4eH//////////////////////////////////////////////////////////////////////////////////////////////////////6urq/+ampr/0NDQ/3d3d//9/f3/rMfw/9nl+P+zzPH/9vb2/2RkZP/c3Nz/eXl5/9jY2P//////////////////////////////////////////////////////////////////////////////////////////////////////9/f3/5mZmf+Li4v/5OTk/+Hr+f+Msuv/ydv1/42y6//u9Pz/ysrK/4aGhv+0tLT//Pz8/////////////////////////////////////////////////////////////////////////////////////////////////////////////Pz8//j4+P/4+v3/XJHi/+Xt+v//////irHq/7nQ8//+/v7/9fX1//7+/v///////////////////////////////////////////////////////////////////////////////////////////////////////////9nZ2f9ra2v/b29v/7e3t//k7fr/bp3l/6C/7v+xyvH//Pz8/42Njf91dXX/eHh4//Dw8P//////////////////////////////////////////////////////////////////////////////////////////////////////o6Oj/7a2tv/t7e3/bW1t//b4/P/U4vf/4Or5/+nw+//z8/P/ZmZm//b29v+FhYX/09PT///////////////////////////////////////////////////////////////////////////////////////////////////////g4OD/eXl5/3l5ef+/v7///Pz8/6Kiov+FhYX/vr6+//39/f+Xl5f/gYGB/4WFhf/z8/P////////////////////////////////////////////////////////////////////////////////////////////////////////////4+Pj/9PT0///////Ozs7/hoaG/97e3v9tbW3/6+vr//39/f/w8PD//f39/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+fn5/9vb2//mpqa/3d3d//09PT//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+Dg4P/IyMj/7e3t////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
rel="icon" type="image/x-icon" />
</head>
<body>
<div class="container">
<nav class="nav">
<h1>
<a class="brand-logo" href="index.html">Photo Gallery</a>
</h1>
</nav>
<!-- IMAGE search box-->
<div class="header">
<div>
<h3 class="text-center">Search For Any Image</h3>
<form id="searchForm" autocomplete="off">
<input type="text" class="form-control" id="searchText" placeholder="Search Image Here">
</form>
<h4 class="from-pixabay">Images from Pixabay</h4>
</div>
<div class="paginations">
Previous
<p class="pageNumber">Page 1</p>
Next
</div>
</div>
<!-- IMAGES GO HERE -->
<div class="masonry">
</div>
</div>
<!-- Pre-footer -->
<!--SECTION Contact-Footer -->
<footer class="footer-section" id="contact">
<div class="rows-container">
<div class="footer-con">
<div class="homepage-link">
<a href="http://rkdevelopment.org" target="_blank">
<h3>Rkdevelopment.org</h3>
</a>
</div>
<ul class="social-list center">
<li>
<a href="https://github.com/RexfordK" target="_blank">
<i class="ion-social-github"></i>
</a>
</li>
<li>
<a href="https://www.linkedin.com/in/rexford-koduah" target="_blank">
<i class="ion-social-linkedin"></i>
</a>
</li>
<li>
<a href="https://www.freecodecamp.org/rexfordk" target="_blank">
<i class="ion-fireball"></i>
</a>
</li>
</ul>
<p>Copyright © 2018 by Rexford Koduah. All rights reserved.</p>
</div>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://unpkg.com/imagesloaded#4/imagesloaded.pkgd.min.js"></script>
<script src="resources/js/main.js"></script>
</body>
</html>
Every time you call getPage, you are adding another $("#pagination2").click handler. Which means the first time you click it, you do one ajax request. The second time you do two, the third time you do three, etc. You need to either only setup the click handler once, and make sure your logic reflects that, or clear the old one each time with $("#pagination2").off('click').click(

Refresh output with a button instead of reloading the page

i'm making a website where I need a randomised output. I have a working solution using Javascript but the only way the output is changing at the moment is by reloading the page. Is there anything that I can do to reload the output without reloading the page (preferably using a button)?
My current code:
<DOCTYPE html>
<html>
<head>
<title>Strat Roulette - R6S Edition</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="strats.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
var request = new XMLHttpRequest();
request.onload = function() {
// get the file contents
var fileContent = this.responseText;
// split into lines
var fileContentLines = fileContent.split( '\n' );
// get a random index (line number)
var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
// extract the value
var randomLine = fileContentLines[ randomLineIndex ];
// add the random line in a div
document.getElementById( 'strats-output' ).innerHTML = randomLine;
};
request.open( 'GET', 'strats.txt', true );
request.send();
</script>
</head>
<body>
<div id="content">
<div class="textshadow">
<h1>Strat Roulette</h1>
<h2>Rainbow 6 Siege Edition</h2>
</div>
<div id="strat">
<code><div id="strats-output"></div></code>
</div>
<button type="button" class="btn btn-primary" onClick="window.location.reload()">Gimme New Strat</button>
</div>
</body>
<footer style="clear: both;">
<p class="alignleft">© Skiletro <?php echo date("Y"); ?></p> <p class="alignright">strats.txt</p>
</footer>
</html>
function sendRequest(){
var request = new XMLHttpRequest();
request.onload = function() {
// get the file contents
var fileContent = this.responseText;
// split into lines
var fileContentLines = fileContent.split( '\n' );
// get a random index (line number)
var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
// extract the value
var randomLine = fileContentLines[ randomLineIndex ];
// add the random line in a div
document.getElementById( 'strats-output' ).innerHTML = randomLine;
};
request.open( 'GET', 'strats.txt', true );
request.send();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="strats.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
</script>
<div id="content">
<div class="textshadow">
<button onclick="sendRequest()">REFRESH CONTENT</button>
<h1>Strat Roulette</h1>
<h2>Rainbow 6 Siege Edition</h2>
</div>
<div id="strat">
<code><div id="strats-output"></div></code>
</div>
<button type="button" class="btn btn-primary" onClick="window.location.reload()">Gimme New Strat</button>
</div>
</body>
<footer style="clear: both;">
<p class="alignleft">© Skiletro <?php echo date("Y"); ?></p> <p class="alignright">strats.txt</p>
</footer>
Moreover, you may also additionally call it onLoad.
Simply just add the request thing into a function and call it on button click.
Just wrap your AJAX code in a function, and have that function being called when the button is pressed:
function reloadData(){
var request = new XMLHttpRequest();
request.onload = function() {
// get the file contents
var fileContent = this.responseText;
// split into lines
var fileContentLines = fileContent.split( '\n' );
// get a random index (line number)
var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
// extract the value
var randomLine = fileContentLines[ randomLineIndex ];
// add the random line in a div
document.getElementById( 'strats-output' ).innerHTML = randomLine;
};
request.open( 'GET', 'strats.txt', true );
request.send();
}
Then
<button type="button" class="btn btn-primary" onClick="reloadData()">Gimme New Strat</button>
See codepen:

Categories