User Frontend Selection That Loads Images From Database With Django - javascript

I have a drop down bar with a multi selection tool. A user picks from titles of graphs stored in a model for the graphs they want to display. How can I use those selections to display these graphs? I am using Ajax to send the data to the backend. From that data I created a new context_dict full of the model objects we want displayed. I want to either display in the same template or link to another template that can use this context dict. I do not know the best way to do this. Here is some of my code below.
Models:
from django.db import models
class ChartPrac(models.Model):
title = models.CharField(max_length=256)
chart = models.ImageField()
def __str__(self):
return self.title
Views:
def querier(request):
if request.method == 'POST':
options_arr = request.POST.get('optionsArr')
options = options_arr.split(':')
options = options[1:]
print(options)
context_arr = []
context_graphs = {}
i = 0
for elements in options:
charts_to_display = ChartPrac.objects.get(title=elements)
context_arr.append(charts_to_display)
i += 1
context_graphs['titles'] = context_arr
return HttpResponse(options_arr)
else:
graph_titles = ChartPrac.objects.all()
context_dict = {'titles': graph_titles}
print(context_dict)
print(type(context_dict['titles']))
return render(request, 'graph_querier/base.html', context=context_dict)
Urls:
from django.urls import path
from graph_querier import views
app_name = 'graph_querier'
urlpatterns = [
path('', views.index, name='index'),
path('querier/', views.querier, name='querier'),
# path('graph/', views.graph, name='graph'),
]
Template:
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>Marketing Querier</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="https://res.cloudinary.com/dxfq3iotg/raw/upload/v1569006288/BBBootstrap/choices.min.css?version=7.0.0">
<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://res.cloudinary.com/dxfq3iotg/raw/upload/v1569006273/BBBootstrap/choices.min.js?version=7.0.0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="{% static 'graph_querier\querier.css' %}">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: rgba(0,96,155,255)";>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'main_dash:main_dash' %}">Main Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Marketing Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Sales Dashboard</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Input</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Input</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Input</a>
</li>
</ul>
</div>
</nav>
<div id="title">
<h1 id="graph-querier-text">Graph Querier</h1>
</div>
<div class="row d-flex justify-content-center mt-100" id='search'>
<div class="col-md-6"> <select class="select-option" id="choices-multiple-remove-button" placeholder="Select up to 10 Graphs" multiple>
{% for graphs in titles %}
<option class="option-rend" value={{ graphs.title }}>{{ graphs.title }}</option>
{% endfor %}
</select> </div>
</div>
<script>
$(document).ready(function(){
var multipleCancelButton = new Choices('#choices-multiple-remove-button', {
removeItemButton: true,
maxItemCount:10,
searchResultLimit:1000,
renderChoiceLimit:1000
});
});
</script>
<script src="{% static '\graph_querier\javascript\base.js' %}"></script>
<div id='render-graphs'>
<button type="button" class="btn btn-primary btn-lg" onclick='rendGraphs();'>Render Graphs</button>
{% csrf_token %}
</div>
</body>
</html>
JS:
function rendGraphs(){
var select = document.getElementById('choices-multiple-remove-button');
var csrf = $("input[name=csrfmiddlewaretoken]").val();
var optionsArr = [];
for (var x = 0; x < select.length; x++){
var temp = select.options[x].text;
optionsArr.push(temp);
}
var stringOptions = ''
for (var i= 0; i < optionsArr.length; i++){
var stringOptions = stringOptions.concat(":" + String(optionsArr[i]));
}
$.ajax({
url: '/query/querier/',
type: 'POST',
data: {'optionsArr': stringOptions,
'csrfmiddlewaretoken': csrf
}
}).done(function(response){
console.log(response)
});
}

Related

Connect javascript file with django in static file

Solved - problem was in django and js file. After repair django i don't check console in my Web browser which show issue in on js file. THank you everyone for help.
Update - refresh content of files after changes
I attach a js file to my Django but have problem bcz JS don't works on website view, when CSS file style Django see. I try looks some toturial but still the same problem. Arrow etc don;t react on any click.
settings.py
import os
from pathlib import Path
import dotenv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
dotenv.load_dotenv()
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG") == "True"
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'accounts',
'turbineweb',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Turbine_power_Web.urls'
'''
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
'''
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'libraries': {
'staticfiles': 'django.templatetags.static',
}
},
},
]
WSGI_APPLICATION = 'Turbine_power_Web.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, '../turbineweb/static')]
#STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'accounts.User'
LOGIN_REDIRECT_URL = 'home_page'
LOGOUT_REDIRECT_URL = 'home_page'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
urls.py in project
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls')),
path('', include('turbineweb.urls')),
]
urls.py in app
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = [
path('home/', views.home_page, name='home_page'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
template:
<! DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Turbine Power Web </title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="TurbinePowerWeb let u choose turbine model adding by turbine manufacturer
and check their energy production in a given period of time"/>
<link href="/static/css/style.css" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<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>
</head>
<body>
<section>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg bg-dark navbar-dark ">
<!-- Container wrapper -->
<div class="container-fluid justify-content-center">
<!-- Navbar brand -->
<a class="navbar-brand" href="/home/"> Turbine Power Web</a>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ms-auto">
<li class="nav-item"><a class="nav-link" href="/logout/">Logout</a></li>
<li class="nav-item"><a class="nav-link" href="/password-change/">Change Password</a></li>
<li class="nav-item"><a class="nav-link" href="">Turbine Models</a></li>
<li class="nav-item"><a class="nav-link" href="">Author</a></li>
<li class="nav-item"> Hello, Tester </li>
</ul>
</div>
</div>
</nav>
</section>
<div class="bg">
<main>
<div id="slider">
<div id="top-row">
<img class="arrow left-class" id="arrow-left" src="/static/image/arrow-left.png" />
<div id="slides-container">
<img class="slide active" src="/static/image/about-us.png">
<img class="slide" src="/static/image/turbine-models.png">
<img class="slide" src="/static/image/calculate-power.png">
</div>
<img class="arrow right-class" id="arrow-right" src="/static/image/arrow-right.png" />
</div>
<div id="bottom-row">
<div id="dots">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</div>
</div>
<script src="/static/js/home_page.js"></script>
</main>
</body>
</html>
js file:
let activeSlideNumber = 1;
let arrowLeft = document.getElementById('arrow-left')
let arrowRight = document.getElementById('arrow-right')
let hideActiveSlide = () => {
let activeElement = document.querySelector('.active');
activeElement.classList.remove('active')
}
let showSlide = (slideNumber) => {
hideActiveSlide();
document.querySelector('#slide'+slideNumber).classList.add('active')
}
let showNextSlide = () => {
if(activeSlideNumber === 3) {
activeSlideNumber = 1;
} else {
activeSlideNumber = activeSlideNumber + 1;
}
showSlide(activeSlideNumber);
};
let showPreviousSlide = () => {
if(activeSlideNumber === 1) {
activeSlideNumber = 3;
} else {
activeSlideNumber = activeSlideNumber - 1;
}
showSlide(activeSlideNumber);
};
for(let i = 1; i <= 3; i++) {
let showSlideI = () => {
activeSlideNumber = 1;
showSlide(i)
};
document.querySelector('#dol'+i).addEventListener('click', showSlideI);
}
arrowLeft.addEventListener('click', showNextSlide);
arrowRight.addEventListener('click', showPreviousSlide);
Projecy view:
Turbine_power_Web (project)
settings.py
urls.py
accounts (app)
turbineweb(app)
static
css
style.css
image
images.png
js
home_page.js
templates
turbineweb
home_page.html
init.py
admin.py
models.py
urls.py
manage.py
on Terminal get error:
WARNINGS:
?: (staticfiles.W004) The directory 'C:\Users\Dom\Desktop\Python_Project\django_proejct_magisterka\Turbine_power_Web\../turbineweb/static' in the STATICFILES_DIRS setting does not exist.
I think I found the solution. We were looking at the wrong place. Your Django settings are correct. It's your js file which selects the wrong button:
Change:
let arrowLeft = document.querySelector('.arrow-left')
let arrowRight = document.querySelector('.arrow-right')
To:
let arrowLeft = document.getElementById('arrow-left')
let arrowRight = document.getElementById('arrow-right')
Edit
I took a closer look at your js file and found some missing selectors.
I've added id="sliderX" and id="dotX". Without them your js threw an error and was never executed.
<main>
<div id="slider">
<div id="top-row">
<img class="arrow left-class" id="arrow-left" src="/static/image/arrow-left.png" />
<div id="slides-container">
<img class="slide active" id="slide1" src="/static/image/about-us.png">
<img class="slide" id="slide2" src="/static/image/turbine-models.png">
<img class="slide" id="slide3" src="/static/image/calculate-power.png">
</div>
<img class="arrow right-class" id="arrow-right" src="/static/image/arrow-right.png" />
</div>
<div id="bottom-row">
<div id="dots">
<div class="dot" id="dot1"></div>
<div class="dot" id="dot2"></div>
<div class="dot" id="dot3"></div>
</div>
</div>
</div>
<script src="/static/js/home_page.js"></script>
</main>
I didn't change your js other then the change I mentioned at the top of this post.
Sidenote: Rightclick in your Chrome Browser > Inspect and then at the top of the Sidebar click of "Console". Here you will see all js erros including reference for debugging.
instead of this:
<script src="{% static 'js/home_page.js' %}"></script>
try this:
<script src="{% static '/js/home_page.js' %}"></script>
And correct your typo sttatic to static
In settings file:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
Also in TEMPLATES in settings file, add it:
'libraries' : {
'staticfiles': 'django.templatetags.static',
}
EX:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'libraries' : {
'staticfiles': 'django.templatetags.static', #Added here
}
},
},
]
in my urls.py i configurate static but thats not help - answering on Sunderam Dubey comment
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = [
path('home/', views.home_page, name='home_page'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
after add in setttings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
needed to remove STATIC_ROOT
Ctrl + U give me it:
<! DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Turbine Power Web </title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="TurbinePowerWeb let u choose turbine model adding by turbine manufacturer
and check their energy production in a given period of time"/>
<link href="/static/css/style.css" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<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>
</head>
<body>
<section>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg bg-dark navbar-dark ">
<!-- Container wrapper -->
<div class="container-fluid justify-content-center">
<!-- Navbar brand -->
<a class="navbar-brand" href="/home/"> Turbine Power Web</a>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ms-auto">
<li class="nav-item"><a class="nav-link" href="/logout/">Logout</a></li>
<li class="nav-item"><a class="nav-link" href="/password-change/">Change Password</a></li>
<li class="nav-item"><a class="nav-link" href="">Turbine Models</a></li>
<li class="nav-item"><a class="nav-link" href="">Author</a></li>
<li class="nav-item"> Hello, Tester </li>
</ul>
</div>
</div>
</nav>
</section>
<div class="bg">
<main>
<div id="slider">
<div id="top-row">
<img class="arrow left-class" id="arrow-left" src="/static/image/arrow-left.png" />
<div id="slides-container">
<img class="slide active" src="/static/image/about-us.png">
<img class="slide" src="/static/image/turbine-models.png">
<img class="slide" src="/static/image/calculate-power.png">
</div>
<img class="arrow right-class" id="arrow-right" src="/static/image/arrow-right.png" />
</div>
<div id="bottom-row">
<div id="dots">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</div>
</div>
<script src="/static/js/home_page.js"></script>
</main>
</div>
</body>
</html>

Uncaught Syntax Error: Unexpected identifier game.js:25

I'm making my first flask app which is a text adventure and a separate section to leave a review. I'm trying to follow along with a text adventure tutorial. I've got my site running however when I refresh the page to see my progress the changes in game.js are not reflected and I'm met with the error in the title.
This is my first post on Stack Overflow so I've put all of my code below. Thanks in advance for any help! I'm still relatively new so sorry for any stupid mistakes, Paddy.
game.js
const textElement = document.getElementById('text')
const optionsButtonsElement = document.getElementById('options-buttons')
let state = {}
function startGame() {
state = {}
showTextNode(1)
}
function showTextNode(textNodeIndex) {
const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
textElement.innerText = textNode.text
while (optionsButtonsElement.firstChild)
optionsButtonsElement.removeChild(optionsButtonsElement.firstChild)
}
function selectOption(option) {
}
const textNodes = [
{
id:1
text: 'You wake up staring at the ceiling of your bunker.',
options [
{
text: 'Turn on the radio',
nextText: 2
},
{
text: 'Grab your pistol and pack up the remainder of your supplies.',
}
]
}
]
startGame()
game.html
{% block title %}Get ready to play!{% endblock %}
{% block content %}
<body>
<div class="container">
<div id="text">Text</div> <br/>
<div id="option-buttons" class="btn-grid">
<button type="button" class="btn btn-outline-dark btn-lg btn-block">Option 1</button>
<button type="button" class="btn btn-outline-dark btn-lg btn-block">Option 2</button>
<button type="button" class="btn btn-outline-dark btn-lg btn-block">Option 3</button>
<button type="button" class="btn btn-outline-dark btn-lg btn-block">Option 4</button>
<script src="{{ url_for('static', filename='js/game.js')}}"></script>
</div>
</body>
{% endblock %}
app.py
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
#Initialising the database
db = SQLAlchemy(app)
#Creating a database model
class Posts(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
#Creating a function to return a string when a post is added to db
def __repr__(self):
return '<Content %r>' % self.id
#app.route('/')
def index():
return render_template("index.html")
#app.route('/game')
def game():
return render_template("game.html")
#app.route('/blog', methods=['POST', 'GET'])
def blog():
if request.method == "POST":
post_content = request.form['content']
new_post = Posts(content=post_content)
try: #Push the blog post to the db
db.session.add(new_post)
db.session.commit()
return redirect('/blog')
except:
return "There was an error adding your post"
else:
posts = Posts.query.order_by(Posts.date_created)
return render_template("blog.html", posts=posts)
#app.route('/update/<int:id>' , methods=['POST', 'GET'])
def update(id):
post_to_update = Posts.query.get_or_404(id)
if request.method == "POST":
post_to_update.content = request.form['content']
try:
db.session.commit()
return redirect('/blog')
except:
return "There was a problem updating your blog post"
else:
return render_template('update.html', post_to_update=post_to_update)
#app.route('/delete/<int:id>')
def delete(id):
post_to_delete = Posts.query.get_or_404(id)
try:
db.session.delete(post_to_delete)
db.session.commit()
return redirect('/blog')
except:
return "There was a problem deleting this post :("
my base.html template
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<title>
{% block title %}GEN TITLE{% endblock %}
</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{{ url_for('index')}}">Patricks Site</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{{ url_for('index')}}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('game')}}">Game</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('blog')}}">Blog</a>
</li>
</ul>
</div>
</nav>
</br>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<!-- Option 2: jQuery, Popper.js, and Bootstrap JS
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
-->
{% block content %}
{% endblock %}
</body>
</html>
Sorry for the wall of text, I wasn't quite sure how much I should show. Thanks
Your error is telling you to look at line 25 of game.js.
It appears you're missing a colon on that line, after options, and a comma after id: 1. You have:
const textNodes = [
{
id:1
text: 'You wake up staring at the ceiling of your bunker.',
options [...],
You need:
const textNodes = [
{
id:1,
text: 'You wake up staring at the ceiling of your bunker.',
options: [...],

Flask: why isn't AJAX being called when form is submitted?

I'm making a web application with flask that takes a submitted value from a form and, sends it to a python function, and returns the response to html.
main.py:
app = Flask(__name__)
#app.route('/')
def index():
return render_template("index.html")
#app.route('/', methods=['POST'])
def search_form():
print(request.form)
x = request.form['searchinput']
a = Vbulletin(x)
#a.reg_ver()
def result_gen():
return a.reg_ver()
result_gen()
temp = []
for s in result_gen():
text = s
print(text)
I want to use ajax to send the form to flask. I know I can just use html to handle the form, but i want to figure out how to do it with ajax.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>UserFind Home</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">
<script type="text/javascript" src="{{ url_for('static', filename='search.js') }}"></script>
</head>
<body>
<nav>
<ul id="navlist">
<h1>Userfind</h1>
<li><a class="btn" href="#home">Home</a></li>
<li><a class="btn" href="#contact">Contact</a></li>
<li><a class="btn" href="#about">About</a></li>
<form name=searchbar>
<ul id="navsearch">
<li class="search">
<input type="text" id="searchinput" name="searchinput" placeholder="Search for User here. Must be atleast 5 characters long.">
</li>
<li><button type="submit" class="btn-default">Submit</button></li>
</ul>
</form>
</ul>
</nav>
<p>{{ text }}</p>
<div class="footer">
<p>©2019 Userfind</p>
</div>
</body>
</html>
I know I can just add the method like:
<form method="POST" name=searchbar>
But im trying to learn how to do it with jquery/ajax.
search.js:
$(document).ready(function() {
$('form').on('submit', function(event) {
event.preventDefault();
$.ajax({
data : {
x : $('#searchinput').val(),
console.log(x)
},
type : 'POST',
url : '/'
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#successAlert').text(data.x).show();
$('#errorAlert').hide();
}
});
});
});
I've tried several different ways but ajax is never call. When i inspect the html no ajax is present on the form either. It just sends a get request. So how can fix this so AJAX is called when I submit the form?
$('form').on('click', function(event) {
event.preventDefault();
$.ajax({
data: {
x: $('#searchinput').val()
},
type: 'POST',
url: '/',
success: function() {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
} else {
$('#successAlert').text(data.x).show();
$('#errorAlert').hide();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>UserFind Home</title>
<link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">
<script type="text/javascript" src="{{ url_for('static', filename='search.js') }}"></script>
</head>
<body>
<nav>
<ul id="navlist">
<h1>Userfind</h1>
<li><a class="btn" href="#home">Home</a></li>
<li><a class="btn" href="#contact">Contact</a></li>
<li><a class="btn" href="#about">About</a></li>
<form method="POST" name="searchbar">
<ul id="navsearch">
<li class="search">
<input type="text" id="searchinput" name="searchinput" placeholder="Search for User here. Must be atleast 5 characters long.">
</li>
<li><button type="button" class="btn-default">Submit</button></li>
</ul>
</form>
</ul>
</nav>
<p>{{ text }}</p>
<div class="footer">
<p>©2019 Userfind</p>
</div>
</body>
</html>
I had my code set up to click form instead of button.
I changed:
$('form').on('click', function(event)
to this:
$("#submit").click(function(e)
In flask I also had to change:
x = request.form['searchinput']
to:
x = request.form['id']
because that was what data was being passed to flask as.
In the end js looked like this:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/",
data: { id: $("#searchinput").val()},
success:function(){
alert("POST was sent.");
}
})
});
});

Traversing the DOM. How to get onclick value from a li

I am really stuck. I have tried lots of things but none are working. I am trying to store the value of onclick event from a . I think I am getting my parent & child nodes confused but have spent so long on it I am now super confused and now completely stuck and nothing is making sense.
here is my code so far
/* random word generator */
function pickWord() {
let words = [
'dog',
'horse',
'kitchen',
'javascript',
'computer',
'programming',
'chair',
'towel',
'music',
'zoo',
'oxygen'
];
return words[Math.floor(Math.random() * words.length)];
}
/* display word.length when start button is clicked */
const startButton = document.getElementById('game-button');
startButton.onclick = () => {
const word = pickWord();
const answerArray = displayWord(word);
document.getElementById('game-word').innerHTML = answerArray;
return answerArray;
}
function displayWord(word) {
const answerArray = [];
for (let i = 0; i < word.length; i++) {
answerArray[i] = "_";
}
return answerArray.join(" ");
}
const getGuess = document.getElementsByClassName('game-letters');
getGuess.onclick = () => {
const input = getGuess.value // stuck here
}
console.log(getGuess)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hangman</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/typed.js#2.0.9"></script>
<script type="text/javascript" src="script.js" async=""></script>
<script type="text/javascript" src="typed.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nova+Flat|Nova+Slim" rel="stylesheet">
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-12">
<h1 class="header">H A N G M A N</h1>
<div class="id-strings">
<h3 class="typed-text"><span id="typed"></span></h3>
</div>
<div id="game">
<ul id="game-list">
<li class="game-letters">A</li>
<li class="game-letters">B</li>
<li class="game-letters">C</li>
<li class="game-letters">D</li>
<li class="game-letters">E</li>
<li class="game-letters">F</li>
<li class="game-letters">G</li>
<li class="game-letters">H</li>
<li class="game-letters">I</li>
<li class="game-letters">J</li>
<li class="game-letters">K</li>
<li class="game-letters">L</li>
<li class="game-letters">M</li>
<li class="game-letters">N</li>
<li class="game-letters">O</li>
<li class="game-letters">P</li>
<li class="game-letters">Q</li>
<li class="game-letters">R</li>
<li class="game-letters">S</li>
<li class="game-letters">T</li>
<li class="game-letters">U</li>
<li class="game-letters">V</li>
<li class="game-letters">W</li>
<li class="game-letters">X</li>
<li class="game-letters">Y</li>
<li class="game-letters">Z</li>
</ul>
</div>
<div id="game-word"></div>
<div id="game-begin">
<button id="game-button">Start Game</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
You need to attach event listener to every specific instance of game-letters class
Also, you cannot use getGuess as value, you have to pass that object as this argument
Example: instead doing this
const getGuess = document.getElementsByClassName('game-letters');
getGuess.onclick = () => {
const input = getGuess.value // stuck here
}
Do this:
for (let i = 0; i < getGuess.length; i++) {
getGuess[i].addEventListener("click", (this) => {
const inputValue = this.textContent;
console.log(inputValue);
});
}
Thefunction currently alerts but you can use as you want
function theFunction(e)
{ alert(e.target.innerHTML);}
<head>
<meta charset="UTF-8">
<title>Hangman</title>
<link rel="stylesheet" =
</head>
<body onclick="theFunction(event)">
<div class="wrapper">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-12">
<h1 class="header">H A N G M A N</h1>
<div class="id-strings">
<h3 class="typed-text"><span id="typed"></span></h3>
</div>
<div id="game">
<ul id="game-list">
<li class="game-letters">A</li>
<li class="game-letters">B</li>
<li class="game-letters">C</li>
<li class="game-letters">D</li>
<li class="game-letters">E</li>
<li class="game-letters">F</li>
<li class="game-letters">G</li>
<li class="game-letters">H</li>
<li class="game-letters">I</li>
<li class="game-letters">J</li>
<li class="game-letters">K</li>
<li class="game-letters">L</li>
<li class="game-letters">M</li>
<li class="game-letters">N</li>
<li class="game-letters">O</li>
<li class="game-letters">P</li>
<li class="game-letters">Q</li>
<li class="game-letters">R</li>
<li class="game-letters">S</li>
<li class="game-letters">T</li>
<li class="game-letters">U</li>
<li class="game-letters">V</li>
<li class="game-letters">W</li>
<li class="game-letters">X</li>
<li class="game-letters">Y</li>
<li class="game-letters">Z</li>
</ul>
</div>
<div id="game-word"></div>
</div>
</div>
</div>
</div>
</body>
</html>

Height of my graph stays the same whatever I do using NVD3 in bootstrap/html

So, I 'm making a school project where we have to make teams of people, who will do activities and shennanigans like that (not that important).
The problem I have here, is that I'm trying to make a graph (at this stage I just imported an example from the NVD3 website, to test everything out). But when I show the graph, the height is set to a very low value, that just makes the graph almost impossible to watch.
I don't know if this is a problem with bootstrap or a problem with D3/NVD3, but I've tried changing the hight value of the graph, set it in class span 6 and stuff. But the problem persists, even If I put the line
<div class = "span6" id="chart1"></div>
outside of the div container. Any one know what I'm doing wrong here?
This is the code of the template for the page itself.
{% extends 'base.html' %}
{% block title %} Team {% endblock %}
{% block toptext %}
<li>MyParameters</li>
<li>MySchedule</li>
<li class = "active">MyTeam</li>
<li class = "dropdown">
Mystats <b class = "caret"></b></span>
<ul class = "dropdown-menu">
<li><a = href = "Mystats_EV.html">MyEffortValues</a></li>
<li><a = href = "Mystats_S.html">MySleep</a></li>
</ul>
</li>
<li>MyAccount</li>
<li>Log Out</li>
{% endblock %}
{% block content %}
<div class = "container">
<div class = "row">
<div class = "col-lg-12">
<h1>{{team.name}}</h1>
<div class = "span6" id="chart1"></div>
<div class="list-group">
{% for staff_member in staff_members %}
<div class = "list-group-item">
<div class = "row">
<div class = "col-md-10">
{{ staff_member }}
</div>
<div class = "col-md-2">
<p>Leider</p>
</div>
</div>
</div>
{% endfor %}
{% for member in members %}
<div class = "list-group-item">
<div class = "row">
<div class = "col-md-10">
{{ member }}
</div>
<div class = "col-md-2">
<p>Teamlid</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
<style>
text {
font: 12px sans-serif;
}
svg {
display: block;
}
#chart1, svg {
margin: 0px;
padding: 0px;
height: 100%;
width: 100%;
display: inline;
}
</style>
<script>
var chart;
nv.addGraph(function() {
chart = nv.models.lineChart()
.options({
transitionDuration: 300,
useInteractiveGuideline: true
}) ;
// chart sub-models (ie. xAxis, yAxis, etc) when accessed directly, return themselves, not the parent chart, so need to chain separately
chart.xAxis
.axisLabel("Time (s)")
.tickFormat(d3.format(',.1f'))
.staggerLabels(true)
;
chart.yAxis
.axisLabel('Voltage (v)')
.tickFormat(d3.format(',.2f'))
;
d3.select('#chart1').append('svg')
.datum(sinAndCos())
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
function sinAndCos() {
var sin = [],
cos = [],
rand = [],
rand2 = []
;
for (var i = 0; i < 100; i++) {
sin.push({x: i, y: i % 10 == 5 ? null : Math.sin(i/10) }); //the nulls are to show how defined works
cos.push({x: i, y: .5 * Math.cos(i/10)});
rand.push({x:i, y: Math.random() / 10});
rand2.push({x: i, y: Math.cos(i/10) + Math.random() / 10 })
}
return [
{
area: true,
values: sin,
key: "Sine Wave",
color: "#ff7f0e"
},
{
values: cos,
key: "Cosine Wave",
color: "#2ca02c"
},
{
values: rand,
key: "Random Points",
color: "#2222ff"
}
,
{
values: rand2,
key: "Random Cosine",
color: "#667711"
}
];
}
</script>
{% endblock %}
This is the base.html, because I did some imports here that might be important.
<!-- i18n loads translation tags -->
{% load i18n %}
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- JQuery -->
<script src="{% static 'jquery/js/jquery-1.11.2.min.js' %}"></script>
<!-- JQueryUI -->
<script src="{% static 'jquery/js/jquery-ui-1.11.4.min.js' %}"></script>
<link href="{% static 'jquery/css/jquery-ui-1.11.4.min.css' %}" rel="stylesheet">
<!-- Bootstrap (js requires jquery) -->
<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet" media="screen">
<link href="{% static 'css/Styles.css' %}" rel="stylesheet">
<script src="{% static "bootstrap/bootstrap.min.js" %}"></script>
<!-- NVD3 -->
<link href="{% static 'd3/build/nv.d3.css' %}" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.min.js" charset="utf-8"></script>
<script src="{% static 'd3/build/nv.d3.js' %}"></script>
{% block extraheader %}{% endblock %}
<title>MyCoach - {% block title %}Home{% endblock %}</title>
</head>
<body class='with-3d-shadow with-transitions'>
<div class = "navbar navbar-inverse navbar-static-top">
<div class = "container">
MyCoach
<button class = "navbar-toggle" data-toggle = "collapse" data-target = ".navHeaderCollapse">
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
<div class = "collapse navbar-collapse navHeaderCollapse">
<ul class = "nav navbar-nav navbar-right">
{% block toptext %}
<li>MyParameters</li>
<li>MySchedule</li>
<li>MyTeam</li>
<li class = "dropdown">
Mystats <b class = "caret"></b></span>
<ul class = "dropdown-menu">
<li><a = href = "Mystats_EV.html">MyEffortValues</a></li>
<li><a = href = "Mystats_S.html">MySleep</a></li>
</ul>
</li>
<li>MyAccount</li>
<li>Log Out</li>
{% endblock %}
</ul>
</div>
</div>
</div>
{% block content %}
{% endblock %}
</body>
</html>
Thnx in advance

Categories

Resources