I'm trying to learn programming from various online tutorials and I created flask server which predicts something. I also got the front-end with javascript but it wont run. I don't know why. I don't know JS. I know python well but that's it.
I don't know that to do.
here is the html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="static/style.css">
<script type="text/javascript", src="static/code.js"></script>
<title>Heading</title>
</head>
<body>
<br>
<!--<img class="logo" src="static/final_v1.png" alt="">-->
<br>
<div class="container main">
<div class="jumbotron" id="holder">
<h1 class='main_heading'> Some Machine learning model</h1>
<h3>lorem ipsum dolor sit amet</h3>
<br>
<div class="instructions">
<h2>Instructions: </h2>
<p>1. lorem ipsum dolor sit amet</p>
<p>2. Curabitur tincidunt orci non nunc sagittis euismod.</p>
</div>
<br>
<br>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Feature1:</label>
<div class="col-sm-10">
<input class="form-control" id="feature1" placeholder=" Enter feature1" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="button btn btn-default">Submit</button>
</div>
</div>
</form>
<h2 class="result"></h2>
</div>
</div>
<!-- Footer -->
<footer class="page-footer font-small blue">
<div class="footer-copyright text-center py-3">
<div class="bottom">
<p>xyz | Status Prediction Demo</p>
</div>
</div>
</footer>
<!-- Footer -->
</body>
</html>
here is the JS file:
var feature1;
$(document).ready(function(){
// fetch all DOM elements for the input
feature1_ = document.getElementById("feature1");
;
});
$(document).on('click','#submit',function(){
alert('end')
// on clicking submit fetch values from DOM elements and use them to make request to our flask API
var feature1 = feature1_.value;
if(feature1 == ""){
// you may allow it as per your model needs
// you may mark some fields with * (star) and make sure they aren't empty here
alert("empty fields not allowed");
}
else{
var requestURL = "http://127.0.0.1/predict?f1="+feature1;
console.log(requestURL); // log the requestURL for troubleshooting
$.getJSON(requestURL, function(data) {
console.log(data); // log the data for troubleshooting
prediction = data['json_key_for_the_prediction'];
});
// following lines consist of action that would be taken after the request has been read
// for now i am just changing a <h2> tag's inner html using jquery
// you may simple do: alert(prediction);
alert(prediction)
$(".result").html("Prediction is:" + prediction);
}
});
There is flask on the backend and js suppose to execute the link.
I have no idea why this is not working
Could you help me please ?
OK, there are several things:
Your submit button is missing an id
Your submit button causes reload
Your callback will run before you get a response
Change your HTML to:
<button id="submit" type="button" type="button" class="button btn btn-default">Submit</button>
The type attribute will remove the reload and the added id will make your script recognize it.
These lines of code runs before you get a response:
alert(prediction)
$(".result").html("Prediction is:" + prediction);
Put them inside getJSON:
$.getJSON(requestURL, function(data) {
console.log(data); // log the data for troubleshooting
var prediction = data['json_key_for_the_prediction']; // <-- added `var`
alert(prediction);
$(".result").html("Prediction is:" + prediction);
});
You're clearly new so I'm offering a strict/minimal test case file for you to work with. This one will simply trigger an alert when the page loads.
Download Notepad++ so you're not adding BOM (Byte Order Marks) if you're running a Microsoft operating system.
Save the following code as example.xhtml.
Modify as needed.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Default Test Template</title>
<script defer="true" type="application/javascript">
//<![CDATA[
window.onload = function(event)
{
alert('JavaScript is enabled');
}
//]]>
</script>
<style type="text/css">
body {background-color: #000; color: #fff;}
</style>
</head>
<body>
<h1>Default Test Template</h1>
</body>
</html>
Related
I can't redirect to the next page. Please help me. I have a project due tomorrow. I've been trying for more than five hours. Please help me. I'm begging you guys. I don't know what I'm doing wrong. I'm very new to Javascript.
Please tell me what I'm doing wrong
document.getElementById("one").onclick = function() {
location.href = "lessons.html"
};
<!DOCTYPE html>
<html>
<head>
<title> MaxFluency Tutorials Page</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="tutorial.css">
</script>
</head>
<body>
<header>
<div class="topbar">
<center>
<p> Tutorials</p>
</center>
</header>
</div>
<div class="lessons">
<center>
<button class=les id=one type="button"> <h3> Lesson 1: </h3> Nature of Communication </button>
<button class=les id="2nd"> <h3>Lesson 2:</h3></button>
<button class="les" id="3rd"> <h3>Lesson 3:</h3></button>
</center>
</div>
<div class="nav">
<center><button class="loc"> Home</button>
<button class="loc"> Highscores </button>
<button class="loc"> Support us!</button>
</center>
</div>
<script type="text/Javascript" src="tutorials.js">
</script>
</body>
</html>
Your HTML is quite malformed, with some opening tags not closed anywhere, closing tags that do not have any matching tag, etc... This needs some tidying.
Also, if this Javascript code is in an external file, make sure it is wrapped in an onload event (making sure that all HTML elements actually loaded before calling document.getElementById). Finally, note the semicolon placement. You should place the semicolon after the statement, not after the function's ending }!
Side note: Why re-inventing the wheel when you can simply use an anchor tag (<a>) for redirecting?
onload = function() {
document.getElementById("one").onclick = function () {
console.log("clicked!");
location.href = "lessons.html";
}
}
<!DOCTYPE html>
<html>
<head>
<title> MaxFluency Tutorials Page</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="tutorial.css">
</head>
<body>
<header>
<div class="topbar">
<center> <p> Tutorials</p> </center>
</div>
</header> <!-- this closing tag was missing -->
<div class="lessons">
<center>
<button class=les id=one type="button" > <h3> Lesson 1: </h3> Nature of Communication </button>
<button class=les id="2nd"> <h3>Lesson 2:</h3></button>
<button class="les" id="3rd"> <h3>Lesson 3:</h3></button>
</center>
</div>
<div class="nav">
<center><button class="loc"> Home</button>
<button class="loc"> Highscores </button>
<button class="loc"> Support us!</button>
</center>
</div>
<script type="text/Javascript" src="tutorials.js"></script>
</body>
</html>
1) there is a lonely closing script tag in the head section.
2) your closing header and div tags before .lessons are in reverse order
3) Here is a fiddle that seems to be working. Button goes to a 404 just because the lessons.html doesn't exist here.
I also added a slash for a relative path. I assume you are probably working from a single root directory given that it is a tutorial but I could be wrong there.
location.href = "/lessons.html";
https://jsfiddle.net/y7txje5c/1/
Im working on a flask app and in my index.html I have a js file that has a smooth scrolling script in it. The smooth scroll works as far as clicking on links and the page goes to that section nice and smooth, but I have a web form that Im trying to process with flask. When I run the app.py and then go to the url it gives my sites loads, but if I fill out the form and submit nothing happens. I get an error in dev console:
uncaught TypeError: Cannot read property 'top' of undefined
at HTMLInputElement.<anonymous> (main.js:33)
at HTMLInputElement.dispatch (jquery-3.4.1.min.js:2)
at HTMLInputElement.v.handle (jquery-3.4.1.min.js:2)
When I comment out the smooth scroll code and run the app, the form works correctly when I click submit. App.py prints out my data and the success page is loaded. The problem is the smooth scroll but I dont know why, because again it actually does smooth scroll but when the code is active but it wont let the submit work.
index.html
<!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">
<script src="https://kit.fontawesome.com/b015121141.js"></script>
<link rel="stylesheet" href="../static/css/style.css">
<link rel="stylesheet" media="screen and (max-width: 768px)" href="../static/css/mobile.css">
<link rel="stylesheet" media="screen and (min-width: 1100px)" href="../static/css/widescreen.css">
<title>System Services</title>
</head>
<body id="home">
<nav id="navbar">
<h1 class="logo">
<span class="text-primary">
<i class="fas fa-robot"></i>
</span>Systems
</h1>
<ul>
<li>Home</li>
<li>What</li>
<li>Who</li>
<li>Contact</li>
</ul>
</nav>
<!-- header: Showcase -->
<header id="showcase">
<div class="showcase-content">
<h1 class="l-heading">
Take me to your leader
</h1>
<p class="lead">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptates alias quasi eligendi. Itaque, repudiandae
obcaecati accusamus harum nesciunt possimus magni?
</p>
Read More
</div>
</header>
<!-- Section: Contact-->
<section id="contact">
<div class="contact-form bg-primary p-2">
<h2 class="m-heading">Contact Us</h2>
<p>Please Use the form below to contact us</p>
<form action="/submit" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Enter Email">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone" placeholder="Enter Phone">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" id="" placeholder="Enter Message"></textarea>
</div>
<input type="submit" value="Submit" class="btn btn-dark">
</form>
</div>
<div class="map"></div>
</section>
<!-- Footer -->
<footer id="main-footer" class="bg-dark text-center py-1">
<div class="container">
<p>Copyright © 2019, All Rights Reserved</p>
</div>
</footer>
<!-- JQuery CDN -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- Local Js file -->
<script src="../static/js/main.js"></script>
<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?key=[api]&callback=initMap"
async defer></script>
</body>
</html>
success.html
<!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>Success</title>
</head>
<body>
<H1>Success!!</H1>
</body>
</html>
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/submit', methods=['POST'])
def submit():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
phone = request.form['phone']
message = request.form['message']
print(name, email, phone, message)
return render_template('success.html')
if __name__ == '__main__':
app.debug = True
app.run()
main.js
//init and add the map
function initMap() {
// your location
const loc = { lat: 42.964890, lng: -88.183040 };
// centered map on location
const map = new google.maps.Map(document.querySelector('.map')
, {
zoom: 10,
center: loc
});
// the marker, positioned at location
const marker = new google.maps.Marker({ position: loc, map: map });
}
// Sticky menu background
window.addEventListener('scroll', function () {
if (window.scrollY > 150) {
document.querySelector('#navbar').style.opacity = 0.88;
} else {
document.querySelector('#navbar').style.opacity = 1;
}
})
// Smooth Scrolling
$('#navbar a, .btn').on('click', function (event) {
if (this.hash !== '') {
event.preventDefault();
const hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top - 100
},
800
);
}
});
The problem is really related on jquery forum and don't came from flask. Nevertheless, they are solutions :
Solution #1:
Use the native css smooth scroll (works fine in your case in my opinion) --> Smooth scroll
Solution #2 :
Try to call animate() in console of your website and paste it belowthe result to see where the problem came from :)
I hope this will help you I tried on my computer and I can figure any other solutions !
You have the line this.hash inside your click event which will always return "" and that is the reason you are getting the error because you have the hash/id in the href attribute of the links and buttons where you are binding the click event
<ul>
<li>Home</li>
<li>What</li>
<li>Who</li>
<li>Contact</li>
</ul>
<input type="submit" value="Submit" class="btn btn-dark">
Read More
and you just need to change the
this.hash
to
$(this).attr('href')
OR
this.href
your click event should look like this
// Smooth Scrolling
$('#navbar a, .btn').on('click', function (event) {
if (this.href !== '') {
event.preventDefault();
const hash = this.href;
$('html, body').animate({
scrollTop: $(hash).offset().top - 100
},
800
);
}
});
I want to create a simple site that can be broken with a Cross-Site Scripting vulnerability. The problem lies in the third and "hard" challenge which filters input with regex and removes everything that starts and ends with angle brackets. So, for example, <img> would be removed, but <img would not. That is also the key to solving the challenge - an unclosed void tag with malicious event attributes. The problem is that the <img tag (or any other unclosed tag) breaks the site but is not added to the DOM.
Everything is done by JavaScript. Clicking a button takes the value of the text box and assigns it to a paragraph's innerHTML. I have already tried other methods like outerHTML, or insertAdjacentHTML() but it all has the same result.
This is the HTML:
<head>
<title>Search</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="stylesheet/stylesheet.css">
<script src="script/xss_hard.js"></script>
</head>
<body>
<div id="top">
<div id="Logo">
<img src="images/logo.png" style="margin-top: 0px; width:150px;display:block" />
<h2><span id="title">Search</span></h2>
</div>
</div>
<div id="logic">
<input type="text" onclick="javascript:clearBox()" value="Search" id="box">
<input type="submit" value="Check" onclick="javascript:submit()" id="butt">
</div>
<p id="searchReflect"></p>
</body>
And this is the corresponding JavaScript:
function submit(){
var reflect = document.getElementById('searchReflect');
var boxText = document.getElementById('box').value;
var blacklist = /<.*>/;
boxText = boxText.replace(blacklist, '');
reflect.HTML = "Your search for \"" + boxText + "\" returned nothing!";
}
The expectation is, is that it is possible to inject e.g. <img src="" onerror="alert(1)" and get an alert popup (XSS). What actually happens is this (taken from Firefox inspector with "Edit as HTML"):
<p id="searchReflect">Your search for "</p>
The strange thing is, is that it breaks the output, but is still not run. Same thing with svg, iframe, or other tags. It SHOULD be, when filtered or properly embedded (innerText, for example):
<p id="searchReflect">Your search for "foo" returned nothing!</p>
You need to improve your code.
<head>
<title>Search</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="stylesheet/stylesheet.css">
<script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
<script src="script/xss_hard.js"></script>
</head>
<body>
<div id="top">
<div id="Logo">
<img src="images/logo.png" style="margin-top: 0px;width:150px;display:block" />
<h2><span id="title">Search</span></h2>
</div>
</div>
<div id="logic">
<input type="text" value="" id="box" placeholder="Search" />
<input type="submit" value="Check" onclick="submit()" id="butt" />
</div>
<p id="searchReflect"></p>
</body>
And corresponding Javascript. I added jQuery in <Head> tag to make code simpler :) Javascript is too long to write so use jQuery instead of Javascript.
function submit(){
var reflect = $('#searchReflect');
var boxText = document.getElementById('box').value;
var blacklist = /<.*>/;
boxText = boxText.replace(blacklist, '');
reflect.html('Your search for \'' + boxText + '\' returned nothing!');
$('#box').val('');
}
I'm fairly new to Javascript I have been playing with some data fetching for the past few days. I created this very simple program (if you can even call it that), where if you click a button, it will generate a div with a random user (using jsonplaceholder API). My issue is, that whenever the button is clicked, it gives me all 10 users at once. I'd like it to give me one user with each click instead. As I said, I am fairly new to JS so I'm not sure how to aproach this (I guess some sort of a loop would be involved?). Any sort of advice, tips or anything would be welcomed ! Thank you !
Here is my code (Using Bootstrap 4 for styling and Axios for data fetching):
const mainButton = document.getElementById('mainButton');
const targetDiv = document.getElementById("targetDiv");
mainButton.addEventListener('click', () => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(function(response) {
let ourRequest = response;
renderData(ourRequest.data);
})
.catch(function(error) {
console.log(error);
});
function renderData(data) {
var stringHTML = "";
for (i = 0; i < data.length; i++) {
stringHTML += `
<div class="col-md-4">
<div class="card">
<div class="card-header">
User ID: #${data[i].id}
</div>
<div class="card-body">
<h4 class="card-title">${data[i].name}</h4>
<p class="card-text">Email - <em>${data[i].email}</em></p>
<p class="card-text">Phone - <em>${data[i].phone}</em></p>
<p class="card-text">Address - <em>${data[i].address.street}, ${data[i].address.city}, ${data[i].address.zipcode}</em></p>
</div>
</div>
</div>
`;
}
targetDiv.insertAdjacentHTML("beforeend", stringHTML);
}
});
<!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">
<link rel="stylesheet" href="main.css">
<title>JSON Users</title>
</head>
<body>
<div class="container">
<div class="text-center my-5">
<h1 class="display-4">Random JSON Users</h1>
<p>This is a random user generator, click the below button to get a
random person!</p>
<button id="mainButton" class="btn btn-primary">Get User!</button>
</div>
<!-- Users -->
<div id="targetDiv" class="row">
</div>
</div>
<!-- JavaScript -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="main.js"></script>
</body>
</html>
If I get it right that your GET method is asking for users, so response contains more that one user. This response you send to renderData method and there you generate your div for each user from response. I supouse to change your GET method to get only one user or send only one user to renderData method like ourRequest.data[0] from your current solution.
I've got this form with bootstrap but I can't find why it's not working properly ant I've no idea why.
HEAD>>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="css/bootstrap-theme.css" rel="stylesheet" type="text/css"/>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="css/corrections.css" rel="stylesheet" type="text/css"/>
<script src="js/JQuery-2.1.1-min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
--> code here
</body>
HTML >>
<div class="col-lg-4">
<form class="form-inline well">
<div class="form-group">
<label class="sr-only" for="text">Some label</label>
<input id="text" type="text" class="form-control" placeholder="Text here">
</div>
<button type="submit" class="btn btn-primary pull-right">Ok</button>
<div class="alert alert-danger" style="display:none">
<h4>Error</h4>
Required amount of letters is 4
</div>
<div class="success alert-success" style="display:none">
<h4>Success</h4>
You have the required amount of letters
</div>
</form>
</div>
JS >>
<script>
$(function () {
$("form").on("submit", function () {
if ($("input").val().length < 4) {
$("div.form-group").addClass("has-error");
$("div.alert").show("slow").delay(4000).hide("slow");
return;
} else if ($("input").val().length > 3) {
$("div.form-group").addClass("has-success");
$("div.success").show("slow").delay(4000).hide("slow");
return;
}
});
});
</script>
the alert class shows everytime, any idea why?
The use of $("input") here is unusual. That selector will pull back all elements on the page that are <input>s, which is almost certainly not what you mean. (If there are other inputs on the page, you might get exactly what you're describing.) Use a more precise selector, like $("#text"), and maybe use debug to output the value of val().length so you know what you're evaluating.
(On a side note, "text" is not a very useful name for a text input, and your else-if seems redundant, but they probably aren't causing problems in your code.)