I am programming an action where after a button press, games on the platform "console" or "pc" is shown. I would like it when the button for "pc" is pressed first, all pc games are shown. And after when the "console" button is pressed, all "pc" games are removed and then all "console" games are appended
code for the buttons is this:
<button class="btn btn-success" type="submit" onclick="searchPC()">PC</button>
<button class="btn btn-success" type="submit" onclick="searchCon()">Console</button>
code for the function is similar across the two buttons;
function searchPC() {
$("search").replaceWith(`<div></div>`);
axios
.get(`${baseUrl}/game/PC`)
.then((response) => {
const posts = response.data;
console.log(posts);
posts.forEach((post) => {
const postPHtml = `
<div class="card sm-6" style="margin-top: 2rem;">
<div class="card-body ">
<p class="card-text">${post.title}</p>
</div>
<div class="card-footer text-muted">
<p>${post.description}</p>
<p>SGD$${post.price}</p>
</div>
<div class="card-footer text-muted">
<a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
</div>
</div>
`;
$("#search").replaceWith(postPHtml);
});
})
.catch((error) => {
console.log(error);
});
}
What I have attempted is to replace any info with an empty div, then adding the desired information, however, it still shows the older information (referring to above, "pc" is still shown even after pressing "console".
Furthermore, I have more than 1 card to add, ie there are >2 sets of information for console and pc games
original file with js included is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Friendbook</title>
<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">
</head>
<body class='bg-dark'>
<div class="container-fluid bg-dark">
<div class="">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<a class="navbar-brand" href="/">
<div>
<img src="http://localhost:8082/images/image.jpg" alt="logo" style="width:40px;" id="logo">
</div>
</a>
<a class="nav-link" href="/">Home</a>
<button class="btn btn-success" type="submit" onclick="searchPC()">PC</button>
<button class="btn btn-success" type="submit" onclick="searchCon()">Console</button>
</nav>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark mt-1">
<form class="form-inline ml-2" action="/action_page.php">
<input class="form-control" id='searchP' type="text" placeholder="Search by Price">
<button class="btn btn-success" type="submit">Search</button>
</form>
<form class="form-inline ml-2" action="/action_page.php">
<input class="form-control" id='searchN' type="text" placeholder="Search by Name">
<button class="btn btn-success" type="submit">Search</button>
</form>
</nav>
<div class="row" style="margin-top: 2rem;">
</div>
</div>
<div class="card" style="margin-top: 2rem;">
<div class="card-body col-md-10">
<h4 class='title '>Search Games</h4>
<div id="search" class="container-fluid md-6 sm-6">
</div>
</div>
</div>
<div class="card" style="margin-top: 2rem;">
<div class="card-body col-md-10">
<h4 class='title '>All Games</h4>
</div>
</div>
<div class="row" style="margin-top: 2rem;">
<div class="col-md-11 col-xs-12 ml-5">
<div id="posts" class="container-fluid md-6 sm-6">
</div>
</div>
</div>
</div>
<footer class='bg-dark p-3'>
<div class='ml-2 mt-2'>
<form>
<button class="btn btn-success" type="submit" onclick="logout()">logout</button>
</form>
</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://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const baseUrl = "http://localhost:8081";
const token = localStorage.getItem("token");
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
if (token === null /* || isNaN(loggedInUserID) */) {
window.location.href = "/login/";
} else {
axios.get(`${baseUrl}/gameall/all`)
.then((response) => {
const posts = response.data;
console.log(posts)
posts.forEach((post) => {
const postHtml = `
<div class="card sm-6" style="margin-top: 2rem;">
<div class="card-body ">
<p class="card-text">${post.title}</p>
</div>
<div class="card-footer text-muted">
<p>${post.description}</p>
<p>SGD$${post.price}</p>
</div>
<div class="card-footer text-muted">
<a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
</div>
</div>
`;
$("#posts").append(postHtml);
});
})
.catch((error) => {
console.log(error);
});
/*
axios.get(`${baseUrl}/game/console/`)
.then((response) => {
const posts = response.data;
console.log(posts)
posts.forEach((post) => {
const postHtml = `
<div class="card sm-6" style="margin-top: 2rem;">
<div class="card-body ">
<p class="card-text">${post.title}</p>
</div>
<div class="card-footer text-muted">
${post.description}
</div>
<div class="card-footer text-muted">
<a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
<p class="card-text">${post.price}</p>
</div>
</div>
`;
$("#posts").append(postHtml);
});
})
.catch((error) => {
console.log(error);
});*/
//acts as addpost api
$("#create-post-form").submit((event) => {
// prevents the page from refreshing
event.preventDefault();
const requestBody = {
text_body: $("#create-post-form-body").val(),
fk_poster_id: loggedInUserID
};
// create the post
axios.post(`${baseUrl}/posts/`, requestBody)
.then((response) => {
// reset form value.
$("#create-post-form-body").val("");
// fetch the post with the returned postID
axios.get(`${baseUrl}/posts/${response.data.postID}`)
.then((response) => {
const post = response.data;
const postHtml = `
<div class="card sm-6" style="margin-top: 2rem;">
<div class="card-body sm-6">
<p class="card-text">${post.text_body}</p>
</div>
<div class="card-footer text-muted">
${post.created_at}
</div>
</div>
`;
$("#posts").append(postHtml);
})
.catch((error) => {
console.log(error);
});
});
});
}
function logout() {
localStorage.removeItem('token')
localStorage.removeItem('role')
localStorage.removeItem('id')
}
function searchPC() {
axios.get(`${baseUrl}/game/PC`)
.then((response) => {
const posts = response.data;
console.log(posts)
posts.forEach((post) => {
const postPHtml = `
<div class="card sm-6" style="margin-top: 2rem;">
<div class="card-body ">
<p class="card-text">${post.title}</p>
</div>
<div class="card-footer text-muted">
<p>${post.description}</p>
<p>SGD$${post.price}</p>
</div>
<div class="card-footer text-muted">
<a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
</div>
</div>
`;
$("#search").appendChild(postPHtml);
});
})
.catch((error) => {
console.log(error);
});
}
function searchCon() {
axios.get(`${baseUrl}/game/console`)
.then((response) => {
const posts = response.data;
posts.forEach((post) => {
const postCHtml = `
<div class="card sm-6" style="margin-top: 2rem;">
<div class="card-body ">
<p class="card-text">${post.title}</p>
</div>
<div class="card-footer text-muted">
<p>${post.description}</p>
<p>SGD$${post.price}</p>
</div>
<div class="card-footer text-muted">
<a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
</div>
</div>
`;
$("#search").appendChild(postCHtml);
});
})
.catch((error) => {
console.log(error);
});
}
</script>
</body>
</html>```
I think you need to use **html(htmlString) **
Description: Set the HTML contents of each element in the set of matched elements
replace $("#search").replaceWith(postPHtml);
with $("#search").html(postPHtml);
see:https://api.jquery.com/html/
Related
I have a problem creating a search box i my JS code. The search needs to find in the restaurant name and the restaurant description. Actually when I search, the code duplicate the cards in my web because my function showRestaurants creates the cards of the web. I don't know how to fix this problem.
The JS code:
import { RestaurantService } from './restaurant-service.class.js';
import '../node_modules/bootstrap/dist/css/bootstrap.css';
import css from '../styles.css';
import RestaurantTemplate from '../templates/restaurant.handlebars';
let restaurants = [];
const restaurantService = new RestaurantService();
const weekdays = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
const currentDay = new Date().getDay();
restaurantService.getAll().then((array) => {
restaurants = array;
restaurants = array.filter((restaurant) => restaurants.id !== restaurant.id);
showRestaurants(restaurants);
});
function createCard(titleName, descriptionText, openDays, cuisineText, phone, image, id) {
// I need a new form to create the cards with handlebars
const objectCard = {
restaurantName: titleName,
restaurantDescription: descriptionText,
restaurantOpenDays: openDays.map(day => weekdays[day]).join(', '),
restaurantOpen: openDays.includes(String(currentDay)),
restaurantCuisine: cuisineText,
restaurantPhoneNumber: phone,
restaurantImageSource: image,
};
const htmlCard = RestaurantTemplate(objectCard);
const container = document.createElement('div');
container.className = 'col';
container.innerHTML = htmlCard;
container.getElementsByTagName('button')[0].addEventListener('click', () => {
if (window.confirm('Are you sure to delete this card?')) {
restaurantService.delete(id).then(() => {
container.remove();
});
}
});
document.getElementById('placesContainer').appendChild(container);
}
function showRestaurants(restaurants) {
for (let index = 0; index < restaurants.length; index++) {
createCard(restaurants[index].name, restaurants[index].description, restaurants[index].daysOpen, restaurants[index].cuisine, restaurants[index].phone, restaurants[index].image ,restaurants[index].id);
}
}
// Search box but actually duplicates the cards that find
document.getElementById('search').addEventListener('keyup', e => {
const searchRestaurant = restaurants.filter(restaurant =>
restaurant.name.toLowerCase().includes(document.getElementById('search').value.toLowerCase()) ||
restaurant.description.toLowerCase().includes(document.getElementById('search').value.toLowerCase()));
showRestaurants(searchRestaurant);
});
The html code:
<html>
<head>
<title>Exercise 3 | Home</title>
<meta charset="UTF-8">
</head>
<body>
<nav class="navbar navbar-expand navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">FoodScore</a>
<ul class="navbar-nav me-auto mb-lg-0">
<li class="nav-item">
<a class="nav-link active" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="new-restaurant.html">New restaurant</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<!--Optional-->
<nav class="navbar navbar-light bg-light justify-content-between mt-3">
<form class="container-fluid">
<input class="form-control" type="text" name="search" id="search" placeholder="Search"
aria-label="Search">
</form>
</nav>
<div id="placesContainer" class="mb-4 mt-2 row row-cols-1 row-cols-md-2 row-cols-xl-3 g-4">
<!-- <div class="col">
<div class="card h-100 shadow">
<img class="card-img-top" src="IMAGE_BASE64">
<div class="card-body">
<button class="btn btn-danger btn-sm float-end">Delete</button>
<h4 class="card-title">Restaurant Name</h4>
<p class="card-text">Restaurant Description</p>
<div class="card-text">
<small class="text-muted">
<strong>Opens: </strong>Mo, Tu, We, Th, Fr, Sa, Su
</small>
<span class="badge ms-2 bg-success">Open</span>
</div>
<div class="card-text">
<small class="text-muted">
<strong>Phone: </strong>999999999
</small>
</div>
</div>
<div class="card-footer">
<small class="text-muted">Cuisine style</small>
</div>
</div>
</div> -->
</div>
</div>
</body>
</html>
The handlebars:
<div class="card h-100 shadow">
<img class="card-img-top" src="{{restaurantImageSource}}">
<div class="card-body">
<button class="btn btn-danger btn-sm float-end">Delete</button>
<h4 class="card-title">{{restaurantName}}</h4>
<p class="card-text">{{restaurantDescription}}</p>
<div class="card-text">
<small class="text-muted">
<strong>Opens: </strong>{{restaurantOpenDays}}
</small>
{{#if restaurantOpen}}
<span class="badge ms-2 bg-success">Open</span>
{{else}}
<span class="badge ms-2 bg-danger">Closed</span>
{{/if}}
</div>
<div class="card-text">
<small class="text-muted">
<strong>Phone: </strong>{{restaurantPhoneNumber}}
</small>
</div>
</div>
<div class="card-footer">
<small class="text-muted">{{restaurantCuisine}}</small>
</div>
</div>
I've tried making a function similar to showRestaurants to filter the array, but is not really necessary because the includes is already in the eventlistener from the search box.
Thanks to James for the clue, I can fix the problem with a function:
function clearRestaurants() {
const everyChildren = document.getElementById('placesContainer').children;
const arrayEveryChildren = Array.from(everyChildren);
for (let index = 0; index < arrayEveryChildren.length; index++) {
arrayEveryChildren[index].remove();
}
}
And adding the function just before the showRestaurants(searchRestaurant)
Currently i am working in a project in which i require specific page views, users and sessions. I have configured out how to fetch it for the whole website using google analytics data api and now i am curious to know about how to do it for specific page.
Below i am attaching my html and js code.
HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<title>Google Analtyics</title>
<!-- Font Awesome -->
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.11.2/css/all.css"
/>
<!-- Google Fonts Roboto -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght#300;400;500;700&display=swap"
/>
<!-- MDB UI KIT -->
<link rel="stylesheet" href="css/mdb.min.css" />
<!-- Custom styles -->
<style></style>
</head>
<body style="background-color: hsl(0, 0%, 96%)">
<!--Main Navigation-->
<header class="mb-10">
<!-- Navbar-->
<nav
class="navbar navbar-expand-lg navbar-light bg-white shadow-2 fixed-top"
>
<div
class="
container-fluid
justify-content-center justify-content-md-between
"
>
<!-- Right elements -->
<ul class="navbar-nav flex-row d-none d-md-flex">
<li class="nav-item me-3 me-lg-1">
<button
id="sign-in-btn"
type="button"
class="btn btn-primary btn-rounded"
style="display: none"
onclick="signIn()"
>
Login
</button>
</li>
<li class="nav-item me-3 me-lg-1">
<button
id="sign-out-btn"
type="button"
class="btn btn-primary btn-rounded"
style="display: none"
onclick="signOut()"
>
Logout
</button>
</li>
<li class="nav-item me-3 me-lg-1">
<button
type="button"
class="btn btn-primary btn-rounded"
style="display: none"
onclick="loadData()"
>
Load Data
</button>
</li>
</ul>
<!-- Right elements -->
</div>
</nav>
<!-- Navbar -->
</header>
<!--Main Navigation-->
<!--Main layout-->
<main>
<div class="container">
<!--Section: Design Block-->
<section class="mb-8">
<h3 class="mb-7 text-center fw-bold">Last 7 days</h3>
<div class="row">
<div class="col-md-4 mb-4 mb-md-0">
<!-- Card -->
<div class="card">
<div
class="
card-body
d-flex
justify-content-start
align-items-center
"
>
<div
class="
bg-primary
text-white
rounded-4
d-flex
justify-content-center
align-items-center
"
style="width: 50px; height: 50px"
>
<i class="fas fa-users fa-lg"></i>
</div>
<div class="ms-3">
<p class="text-muted mb-1">Users</p>
<p class="mb-0">
<span id="displayUsers" class="h4 me-2"></span>
</p>
</div>
</div>
</div>
<!-- Card -->
</div>
<div class="col-md-4 mb-4 mb-md-0">
<!-- Card -->
<div class="card">
<div
class="
card-body
d-flex
justify-content-start
align-items-center
"
>
<div
class="
bg-primary
text-white
rounded-4
d-flex
justify-content-center
align-items-center
"
style="width: 50px; height: 50px"
>
<i class="fas fa-file fa-lg"></i>
</div>
<div class="ms-3">
<p class="text-muted mb-1">Page views</p>
<p class="mb-0">
<span id="displayPageViews" class="h4 me-2"></span>
</p>
</div>
</div>
</div>
<!-- Card -->
</div>
<div class="col-md-4">
<!-- Card -->
<div class="card">
<div
class="
card-body
d-flex
justify-content-start
align-items-center
"
>
<div
class="
bg-primary
text-white
rounded-4
d-flex
justify-content-center
align-items-center
"
style="width: 50px; height: 50px"
>
<i class="fas fa-chart-line fa-lg"></i>
</div>
<div class="ms-3">
<p class="text-muted mb-1">Sessions</p>
<p class="mb-0">
<span id="displaySessions" class="h4 me-2"></span>
</p>
</div>
</div>
</div>
<!-- Card -->
</div>
</div>
</section>
<!--Section: Design Block-->
</div>
</main>
<!--Main layout-->
<!--Footer-->
<footer></footer>
<!--Footer-->
</body>
<!-- MDB ESSENTIAL -->
<script type="text/javascript" src="js/mdb.min.js"></script>
<!-- Google API -->
<script src="https://apis.google.com/js/api.js"></script>
<!-- easyData - Google Analtyics -->
<script type="text/javascript" src="js/easyData-google-analtyics.js"></script>
<!--Fetching data-->
<script>
// Your Client ID
const CLIENT_ID = "";
function loadData() {
// Your GA property ID
const propertyId = "";
const startDate = "7daysAgo";
const endDate = "today";
const metrics = [
{ name: "activeUsers" },
{ name: "screenPageViews" },
{ name: "sessions" },
];
const query = {
dateRanges: [{ startDate, endDate }],
metrics: metrics,
};
runReport(propertyId, query, displayResult);
}
function displayResult(response) {
document.getElementById("displayUsers").innerHTML =
response.result.rows[0].metricValues[0].value;
document.getElementById("displayPageViews").innerHTML =
response.result.rows[0].metricValues[1].value;
document.getElementById("displaySessions").innerHTML =
response.result.rows[0].metricValues[2].value;
}
// Login buttons
document.addEventListener("gapi-loaded", (e) => {
if (isSignedIn()) {
document.getElementById("sign-out-btn").style.display = "block";
document.getElementById("sign-in-btn").style.display = "none";
loadData();
} else {
document.getElementById("sign-in-btn").style.display = "block";
document.getElementById("sign-out-btn").style.display = "none";
}
});
</script>
</html>
JAVASCRIPT CODE
// Google Analytics
const GA_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
const GA_API_URL = "https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta";
gapi.load("client:auth2", function () {
gapi.auth2.init({ client_id: CLIENT_ID }).then(() => document.dispatchEvent(new Event('gapi-loaded')));
});
function signIn(scope = GA_SCOPE) {
return gapi.auth2.getAuthInstance().signIn({ scope }).then(() => {
setCookie('guser-loggedin', 'true', 1);
location.reload();
}, (e) => console.error(e));
}
function signOut() {
return gapi.auth2.getAuthInstance().signOut().then(() => {
setCookie('guser-loggedin', 'true', -1);
location.reload();}, (e) => console.error(e));
}
function loadClient(apiPath = GA_API_URL) {
return gapi.client.load(apiPath);
}
function runReport(propertyId, query, cb = function (res) { console.log(res); }, err = function (err) { console.error(err); }) {
return loadClient().then(() => gapi.client.analyticsdata.properties
.runReport({
property: "properties/" + propertyId,
resource: query
})
.then(cb, err));
}
function isSignedIn() {
if (getCookie('guser-loggedin') === 'true') return true;
return false;
}
function setCookie(cname = 'guser-loggedin', cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Good day to all, I'm new to js, so I would like to ask you, after executing the function, I add a response with content via innerHTML, but this content should also work with javascript, but it works, so I have to restart the page, how to do it right so that my functions work with the added answer?
Need to run this code
document.querySelectorAll('.btn-comment-like, .btn-comment-dislike').forEach((e) =>
e.addEventListener('click', function(e) {
e.preventDefault()
const commentRatingButtons = this;
const commentRatingId = commentRatingButtons.getAttribute('data-id');
const commentRatingAction = commentRatingButtons.getAttribute('data-action');
const commentTotalRating = document.querySelector(`button[data-comment-rating='${commentRatingId}']`);
const commentMessageRating = document.querySelector(`div[data-comment-message='${commentRatingId}']`);
fetch(`/api/comments/${commentRatingId}/${commentRatingAction}/`, {
method: 'POST',
headers: {
"X-CSRFToken": csrftoken,
"X-Requested-With": "XMLHttpRequest",
},
}).then((response) => response.json()).then((result) => {
if (result['error']) {
commentMessageRating.innerHTML = `
<div class="alert alert-danger rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-hexagon-exclamation"></i> ${result['error']}!
</div>`
} else {
if (commentRatingAction === 'like') {
commentMessageRating.innerHTML = `
<div class="alert alert-success rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-face-smile"></i> Спасибо за оценку, ${result['author']}!
</div>`
} else {
commentMessageRating.innerHTML = `
<div class="alert alert-danger rounded-0 shadow-sm me-2 align-self-start mb-2" role="alert" style="padding:2px;">
<i class="fa-solid fa-face-frown"></i> Спасибо за критику, ${result['author']}!
</div>`
}
commentTotalRating.innerHTML = `${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i>`
}
})
})
)
after doing this
commentForm.addEventListener('submit', function(e) {
e.preventDefault()
const commentForm = this;
const commentFormSubmit = commentForm.querySelector('#commentSubmit');
const commentArticleId = commentForm.getAttribute('data-article-id');
const commentEmpty = document.querySelector('#emptyComments');
const commentNestedList = document.querySelector('.nested-comments');
commentFormSubmit.innerText = "Ожидаем добавления...";
commentFormSubmit.disabled = true;
fetch(`/api/articles/${commentArticleId}/comments/create/`, {
method: 'POST',
headers: {
"X-CSRFToken": csrftoken,
"X-Requested-With": "XMLHttpRequest",
},
body: new FormData(commentForm),
}).then((response => response.json()))
.then((result) => {
if (result['comment_is_child']) {
const commentParentThread = document.querySelector(`#comment-thread-${result['comment_parent_id']}`);
commentParentThread.innerHTML += `
<ul id="comment-thread-${result['comment_id']}">
<li>
<div class="card mb-3 nth-shadow border-0 rounded-1">
<div class="card-body">
<div class="row">
<div class="col-md-2 d-none d-sm-inline pe-0">
<img src="${result['comment_avatar']}" class="img-fluid rounded-1 nth-img-comment nth-shadow" alt="{{ node.author.username }}">
</div>
<div class="col-md-10">
<div class="d-flex flex-row gap-2">
<div class="card-title">
<h6 class="nth-card-user-username mb-0">${result['comment_author']}</h6>
</div>
<div class="nth-card-title-username">
${result['comment_created_at']}
</div>
</div>
<div class="card-text mb-2">
${result['comment_content']}
</div>
<div class="d-grid gap-2 d-md-block">
<button class="btn btn-outline-secondary nth-btn-sm btn-like shadow-none" data-id="${result['comment_id']}" data-action="like" type="button">+1 <i class="fa-solid fa-heart-circle-plus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm btn-dislike shadow-none" data-id="${result['comment_id']}" data-action="dislike" type="button">-1 <i class="fa-solid fa-heart-circle-minus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm shadow-none" type="button" data-comment-rating="${result['comment_id']}">${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i></button>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
`
} else {
if (commentEmpty) {
commentEmpty.remove();
}
commentNestedList.innerHTML += `
<ul id="comment-thread-${result['comment_id']}">
<li>
<div class="card mb-3 nth-shadow border-0 rounded-1">
<div class="card-body">
<div class="row">
<div class="col-md-2 d-none d-sm-inline pe-0">
<img src="${result['comment_avatar']}" class="img-fluid rounded-1 nth-img-comment nth-shadow" alt="{{ node.author.username }}">
</div>
<div class="col-md-10">
<div class="d-flex flex-row gap-2">
<div class="card-title">
<h6 class="nth-card-user-username mb-0">${result['comment_author']}</h6>
</div>
<div class="nth-card-title-username">
${result['comment_created_at']}
</div>
</div>
<div class="card-text mb-2">
${result['comment_content']}
</div>
<div class="d-grid gap-2 d-md-block">
<button class="btn btn-outline-secondary nth-btn-sm btn-comment-like shadow-none" data-id="${result['comment_id']}" data-action="like" type="button">+1 <i class="fa-solid fa-heart-circle-plus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm btn-comment-dislike shadow-none" data-id="${result['comment_id']}" data-action="dislike" type="button">-1 <i class="fa-solid fa-heart-circle-minus"></i></button>
<button class="btn btn-outline-secondary nth-btn-sm shadow-none" type="button" data-comment-rating="${result['comment_id']}">${result['comment_total_rating']} <i class="fa-solid fa-hand-holding-heart"></i></button>
</div>
</div>
</div>
</div>
</div>
</li>
</ul>
`
}
commentForm.reset();
commentFormSubmit.innerText = "Добавить комментарий";
commentFormSubmit.disabled = false;
commentFormParentField.value = null;
})
})
I would be very grateful if you direct me to the correctness of creating such methods.
If you are feeling lazy to add it to the function then do something like:
let href = "http://"; //the location of your own html file you are working on.
//This will open your file on a new tab
window.open(href, "_blank");
//This will close your own tab.
window.close();
In this way you can close and open the tab again if it does'nt work with: "window.location.reload".
Put all your js code that you want to reload in a function and simply call it again when you want to. You can also use: window.location.reload();
I'm creating a script that retrieves data from api. everything was successful, but when I wanted to enter another film title it didn't want to refresh the existing data but added new data to the previous data.
function loadContent() {
let $ = jQuery;
let id = $('#titless').val();
var url = "https://api.themoviedb.org/3/search/movie?api_key=b97618b9d94f7f1090189b207f83ce52&language=en-US&query=" + id + "&page=1&include_adult=false";
fetch(url)
.then(res => res.json())
.then(data => {
$.each(data.results, function(i, item) {
$('#atas').each(function() {
$('<div />', {
'class': 'col-md-2 my-2 mx-2 align-center',
'id': 'yaa',
'style': 'border: solid;',
// 'html' : ``,
'html': [
`<img class="card-img-top" src="https://image.tmdb.org/t/p/w600_and_h900_bestv2/${data.results[i].poster_path}">
<h3 class="title">${data.results[i].title}</h3>
<h1 class="title">${data.results[i].id}</h1>
`
],
appendTo: this
})
});
});
});
}
this is my html script
<div class="container">
<h1 class="mt-4">Punten</h1>
<div class="row">
<div class="col bg-dark">
<div class="row">
<div class="col my-4 d-flex justify-content-container">
<input type="text" class="form-control" id="titless">
<button type="submit" class="btn btn-primary ml-4" onclick="loadContent()">Submit</button>
</div>
</div>
<div class="col mb-5">
<div class="card">
<div id="atas" class="card-body row">
</div>
</div>
</div>
</div>
</div>
</div>
You just need to clear the previous content with empty
Also, you don't need the each method over #atas since it's a unique element, just append your new elements like this: $('#atas').append(newElement);
function loadContent() {
let $ = jQuery;
let id = $('#titless').val();
var url = "https://api.themoviedb.org/3/search/movie?api_key=b97618b9d94f7f1090189b207f83ce52&language=en-US&query=" + id + "&page=1&include_adult=false";
fetch(url)
.then(res => res.json())
.then(data => {
/* SOLUTION */
$('#atas').empty();
$.each(data.results, function(i, item) {
$('#atas').append(
$('<div />', {
'class': 'col-md-2 my-2 mx-2 align-center',
'id': 'yaa',
'style': 'border: solid;',
// 'html' : ``,
'html': [
`<img class="card-img-top" src="https://image.tmdb.org/t/p/w600_and_h900_bestv2/${data.results[i].poster_path}">
<h3 class="title">${data.results[i].title}</h3>
<h1 class="title">${data.results[i].id}</h1>
`
]
})
);
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h1 class="mt-4">Punten</h1>
<div class="row">
<div class="col bg-dark">
<div class="row">
<div class="col my-4 d-flex justify-content-container">
<input type="text" class="form-control" id="titless">
<button type="submit" class="btn btn-primary ml-4" onclick="loadContent()">Submit</button>
</div>
</div>
<div class="col mb-5">
<div class="card">
<div id="atas" class="card-body row">
</div>
</div>
</div>
</div>
</div>
</div>
[SOLVED] I had to change the button tag to any other tag like < a > tag to call the function. Such as:
<a class="btn btn-success btn-block" id="bagadd" onclick="return all_check('add', '<?php echo $product_id;?>');"><i class="fa fa-cart-plus"></i> Add To Bag</a>
[Problem]
In my project, am sending out data from a JavaScript to PHP script using an Ajax call. I tried to look for an answer on Stackoverflow, but not success therefor I made a question.
This code is working properly on my chrome browser, but it fails when I try it out in Firefox.
product-detail.php
function all_check(action, productid){
var product_id = productid;
var serial = document.getElementById("showserial").value;
var size = document.getElementById("showsize").value;
var qty = document.getElementById("quantity").value;
var queryString = "";
if(action != "") {
switch(action) {
case "add":
queryString = 'action='+action+'&code='+ product_id+'&serial='+serial+'&quantity='+qty+'&size='+size;
alert(queryString);
break;
case "empty":
queryString = 'action='+action;
break;
}
}
$.ajax({
url: "ajax_action.php",
type: "POST",
dataType:"json",
data: queryString
}).done(function(data){ //on Ajax success
alert("success");
$("#cartcount").html(data.items); //total items in cart-info element
console.log("bla bla bla");
});
}
Here is the button which called this function:
<button class="btn btn-success btn-block" id="bagadd" onclick="return all_check('add', '<?php echo $product_id;?>');"> Add To Bag</button>
On button click, all_check function is called. But on Firefox, ajax call does not work.I checked it by using alert and console inside done function. I cleared cache repeatedly. But it did not work.
Anyone please kindly help me on this problem.
EDIT 1 My firefox version is 54.0 (32-bit).
I am using Google CDN for jQuery :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
EDIT 2
Complete rendered html from firefox:
<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">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<!-- Bootstrap -->
<link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/bootstrap/css/bootstrap-select.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
function all_check(action, productid){ // from 262 line
var product_id = productid;
if(document.getElementById("showsize").value==""){
alert("Please Select size");
return false;
}
else if(document.getElementById("quantity").value==""){
alert("Please Select Quantity");
document.getElementById("quantity").focus();
return false;
}
else{
var qtyid = +document.getElementById("quantity").value;
typeof(qtyid);
var available = +document.getElementById("showavailable").value;
typeof(available);
if(qtyid > available ){
alert("Sorry, Available Quantity is "+ available);
return false;
}
}
console.log("button clicked");
var serial = document.getElementById("showserial").value;
var size = document.getElementById("showsize").value;
var qty = document.getElementById("quantity").value;
var queryString = "";
if(action != "") {
switch(action) {
case "add":
queryString = 'action='+action+'&code='+ product_id+'&serial='+serial+'&quantity='+qty+'&size='+size;
alert(queryString);
break;
case "empty":
queryString = 'action='+action;
break;
}
}
$.ajax({ //make ajax request to cart_process.php
url: "ajax_action.php",
type: "POST",
dataType:"json", //expect json value from server
data: queryString
}).done(function(data){ //on Ajax success
alert("success");
$("#cartcount").html(data.items);
console.log("bla bla bla");
});
}
function get_availble(serial)
{
document.getElementById('showserial').value = serial;
var size_n_available = document.getElementById('product_size').value;
document.getElementById('showsize').value = size_n_available.substring(0,2) ;
document.getElementById('showavailable').value = size_n_available.substring(2) ;
alert(document.getElementById('showavailable').value);
}
</script>
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="col-md-2 col-sm-3 hidden-xs">
<img src="assets/images/logo.png" class="img-responsive" alt="">
</div>
<div class="col-md-7 col-sm-6">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class="form-control input-sm" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-info btn-sm" type="button">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<nav class="navbar navbar-default navbar-static">
<div class="container">
<div class="row">
<div class="navbar-header">
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".js-navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php"><img src="assets/images/logo.png" class="img-responsive" alt="" width="75"></a>
</div>
<div class="collapse navbar-collapse js-navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><i class="fa fa-home"></i></li>
<li class="dropdown">
Category <span class="caret"></span>
<ul class="dropdown-menu dropdown-cart dropdown-content" role="menu">
<li class="">Tote bags</li>
<li class="">Mugs</li>
<li class="">T-shirts</li>
<li class="">Throw Pillow</li>
<li class="">Notebooks</li>
<li class="">Art print</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>About Us</li>
<li>Help</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <span class="glyphicon glyphicon-shopping-cart"></span>
Items <span id="cartcount">
</span>
<span class="caret"></span></a>
<div id="shopping_cart_results"></div>
</li>
</ul>
</div>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="row top-left-message" style="background:#fff">
</div>
</div>
<div class="col-md-1 col-md-offset-2 collapse navbar-collapse js-navbar-collapse">
Artist
</div>
<div class="col-md-1 collapse navbar-collapse js-navbar-collapse">
Home Junction
</div>
</div>
</div>
</div>
<div class="container">
<div class="row" style="margin-top:15px;">
<div class="col-md-5 col-sm-6">
<div id="view-thumb">
<img id="theImg" class="my-foto img-responsive" src="productimage/bigtea-baggin-mugs.jpg" data-large="productimage/bigtea-baggin-mugs.jpg" title="">
</div>
</div>
<div class="col-md-7 col-sm-6">
<div class="productHeader container-fluid">
<div class="row">
<div class="col-sm-8">
<h2>Tea baggin Mug</h2>
</div>
<div class="col-sm-4">
<p style="padding-top: 26px; padding-right:10px; font-family: Helvetica; color:#999; font-size:17px;" class="pull-right">Tk 300</p>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<form action="" method="post">
<div class="form-group">
<select id="product_size" name="product_size" class="form-control" onchange="get_availble(258)" required>
<option value="-1">Select Size</option>
<option value="125">11 oz</option>
<option value="135">15 oz</option>
</select>
<input class="form-control" id="showsize" name="showsize" placeholder="show size" type="text">
<input class="form-control" id="showavailable" name="showavailable" placeholder="show Quantity" type="text">
<input class="form-control" id="showserial" name="showserial" placeholder="show serial" type="text">
</div>
<div class="form-group">
<input class="form-control" id="quantity" name="quantity" placeholder="Enter Quantity" type="text">
</div>
<button class="btn btn-success btn-block" id="bagadd" onclick="return all_check('add', '06020010');"><i class="fa fa-cart-plus"></i> Add To Bag</button>
<input class="btn btn-success btn-block" id="forsubmit" type="hidden">
</form>
</div>
</div>
</div>
<div class="row" style="margin-bottom:10px;">
<div class="col-md-12">
<div class="title">
<h2>Recently viewed</h2>
</div>
<div class="multiple-items recent_view">
<div class="col-md-2 col-sm-6 col-xs-12">
<img src="assets/images/product/because-sloths-1yv-mugs.jpg" class="img-responsive">
</div>
<div class="col-md-2 col-sm-6 col-xs-12">
<img src="assets/images/product/good-morning-i-see-the-assassins-have-failed-mugs.jpg" class="img-responsive">
</div>
</div>
</div>
</div>
</div>
</div>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/bootstrap/js/bootstrap-select.js"></script>
<script src="assets/js/zoomsl-3.0.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" src="slick/slick.min.js"></script>
<script src="assets/js/singleCartDelete.js"></script>
<script>
$(document).ready(function(){
$('.multiple-items').slick({
infinite: true,
slidesToShow: 6,
slidesToScroll: 1,
autoplay: true,
});
$('#thumb-group a').on({
'click': function(){
var imgSrc = $(this).attr('data-src');
$('#theImg').attr('src',imgSrc);
$('#theImg').attr('data-large',imgSrc);
}
});
if(!$.fn.imagezoomsl){
$('.msg').show();
return;
}
else $('.msg').hide();
$('.my-foto').imagezoomsl({
zoomrange: [1, 12],
zoomstart: 4,
innerzoom: true,
magnifierborder: "none"
});
});
</script> <script type="text/javascript" src="assets/js/plugin.js"></script>
This is the ajax_action.php file:
<?php
session_start();
include("connection.php");
if(!empty($_POST["action"])) {
switch($_POST["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productid = mysqli_fetch_row(mysqli_query($con, "SELECT ProductID,ProductName,Price,SerialNo FROM product_info where SerialNo='".$_POST["serial"]."'"));
$product_image = mysqli_fetch_row(mysqli_query($con, "SELECT ImageID, ProductID,BigImage,MidImage,SmallImage,SerialNo FROM product_image
WHERE ProductID='".$productid[0]."' AND SerialNo='".$_POST["serial"]."'"));
$idx = $_POST["serial"].$_POST["size"];
$itemArray = array($idx=>array(
'name'=>$productid[1],
'code'=>$_POST["serial"],
'image'=>$product_image[4],
'quantity'=>$_POST["quantity"],
'price'=>$productid[2],
'size'=>$_POST["size"]
)
);
if(!empty($_SESSION["cart_item"])) {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
$total_items = count($_SESSION["cart_item"]); //count total items
die(json_encode(array('items'=>$total_items))); //output json
}
?>