Python flask script not executing as expected - javascript

I'm trying to execute a function based on a button click via javascript.
I've copied a tutorial on how to do this, but nothing happens.
I've added a break point in the function that should be executed (background_process_test), but the program never executes the function.
What am I missing to get this simple tutorial working?
I'm running on a local machine with waitress.
python code:
from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve
app = Flask(__name__)
#rendering the HTML page which has the button
#app.route('/json')
def json():
return render_template('json.html')
#background process happening without any refreshing
#app.route('/background_process_test')
def background_process_test():
print ("Hello")
return ("nothing")
if __name__ == "__main__":
app.debug = True
serve(app, host='0.0.0.0', port=8080) #WAITRESS!
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<!--<script src="/jquery/jquery-3.6.0.min.js"></script>-->
<script src="{{url_for('static', filename='jquery-3.6.0.min.js')}}"></script>
<script type=text/javascript>
(function() {
('a#test').on('click', function(e) {
e.preventDefault()
$.getJSON('/background_process_test', function(data) {
//do nothing
})
return false;
})
})
</script>
</head>
<body>
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
</body>
</html>
Update:
Network tab

i somehow deleted the '$' sign. It was giving an error due to spacing in visual studio. Setting the spacing right, solved the issue. Many thanks for pointing me in the right direction.

There is a typo in the following code:
('a#test').on('click', function(e) {
...
})
Specifically, your attempt to use jquery get the list of elements that match 'a#test'. The code should be:
$('a#test').on('click', function(e) {
...
})

Related

How to output $.get() method JQuery with Flask

I could not output the data created in Flask to JQuery in a Html page.
I am testing $.get() method in JQuery with Flask. The task is to return a String to a Html page and display it as paragraph. But the result cannot be displayed. Can someone shed a light on this issue. Thanks!
Here is the code in Flask
from flask import request, jsonify, Flask
app = Flask(__name__)
#app.route('/', methods=["GET"])
#app.route('/hello', methods=["GET"])
def hello():
return jsonify('<h1>Hello Flask !!!</h1>')
Here is the html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Events </title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function()
{
$("#btnGet").click(function()
{
//$.get('https://httpbin.org/get',
$.get('http://localhost:5000/hello',
function(data)
{
$("#getInfo").text(data)
});
});
});
</script>
</head>
<body>
<button id="btnGet">Click to Get Info </button>
<p id="getInfo"></p>
</body>
</html>
As new to web programming, after hours trial and error, finally found out that I am not placing the html under static folder and run it in Eclipse Environment. After open it up in http://localhost:5000/static/test.html then it works as expected.

Code dynamic dropdown using Python, sqlite3, HTML and JavaScript

I want to fetch userdata from sqlite DB table and list them as a dropdown list in my HTML code. I am new to Python. I tried writing a code, but it failed. list_fetched is my users list that I fetched from db table.
#app.route('/trail', methods=['POST', 'GET'])
def index():
list_tested = db_dropdown()
return render_template("try.html", trail1=list_fetchted)
return "hi"
try.html:
<html>
<head>
</head>
<body>
<p>Hello World</p>
<button type="submit" onclick="clicked()">Submit</button>
<script>
var trail1 = {{ trail1|tojson }};
function clicked()
{
alert("trail1[0]")
}
</script>
</body>
</html>
No value is getting displayed.
I would recommend looking at the quick start guide for Flask, it may give some advice on your problem and help with your future learning.
(https://flask.palletsprojects.com/en/1.0.x/quickstart/)
I have a solution for your issue (I have removed any sqlite access but sure you can put that in):
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello():
return render_template("try.html", trial1=['1', '2'])
Then your try.html file needs to be placed in /templates/try.html in your project directory. By default this is where Flask references templates.
<html>
<head>
</head>
<body>
<p>Hello World</p>
<button type="submit" onclick="clicked()">Submit</button>
<script>
var trail1 = {{ trial1|tojson }};
function clicked()
{
alert(trail1[0])
}
</script>
</body>
</html>
Enjoy learning python :)

jQuery fileDownload plugin doesn't show popup window, how to fix this?

I'm using jQuery for my frontend part of an application (backend runs on Flask) and I needed a plugin for displaying some kind of information to user while he's waiting for a file to be served to him (and I also need to work with older versions of IE, which is why I've decided to use this plugin).
Unfortunately I haven't been able to do anything with it due to some weird JS errors I'm getting (screens and my example code below).
Example server-side code:
from flask import Flask, send_file, render_template
import os
from time import sleep
app = Flask(__name__)
#app.route('/', methods=['GET'])
def mainRoute():
return render_template('index.html')
#app.route('/filesfordl/file.txt', methods=['GET'])
def fileRoute():
sleep(5) # time for window to appear
fileResponse = send_file(os.path.join(os.getcwd(), 'filesfordl/file.txt'), as_attachment=True, attachment_filename='file.txt')
fileResponse.set_cookie('fileDownload', 'true')
return fileResponse
if __name__ == '__main__':
app.run('0.0.0.0', '5000')
My index.html:
<html>
<head>
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery-3.3.1.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery.fileDownload.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/script.js') }}"></script>
</head>
<body>
Get file!
</body>
</html>
And finally JS part:
/*$.fileDownload('/filesfordl/file.txt', {
successCallback: function (url) {
alert('You just got a file download dialog or ribbon for this URL :' + url);
},
failCallback: function (html, url) {
alert('Your file download just failed for this URL:' + url + '\r\n' +
'Here was the resulting error HTML: \r\n' + html
);
}
});
*/
$(function() {
$(document).on("click", "a.fileDownloadSimpleRichExperience", function() {
$.fileDownload($(this).attr('href'), {
preparingMessageHtml: "We are preparing your report, please wait...",
failMessageHtml: "There was a problem generating your report, please try again."
});
return false; //this is critical to stop the click event which will trigger a normal file download!
});
});
^^ in this part if I uncomment the upper code, it always triggers failCallback after entering index.html even if I don't click on the link.
After clicking the hyperlink i get this error message (can't post images directly yet):
this
Which ultimately leads to this line in the plugin's code.
this
EDIT:
I've added some debugging prints on top of the problematic line:
console.log($("<div>").html(settings.preparingMessageHtml).dialog);
console.log($("<div>").html(settings.preparingMessageHtml));
And output I'm getting after that is.
Any ideas on what I'm doing wrong?
Okay, nevermind, I simply forgot to include jQuery UI files which is the sole reason of my issues, topic can be closed.

How to call node js function from node js client side

I am playing around with an html template and I have noticed that the developer doesn't use RequireJS or anything else to require and call different functions from other node files. Instead, they used this in the html file to initialise and call the function:
<script src="../../assets.js/test.js"></script>
<script type="text/javascript">
$(document).ready(function(){
test.initSomeFunction();
});
</script>
And I've got the below code in assets/js/test.js which defines initSomeFunction in javascript:
test = {
initSomeFunction: function() {
//Some code
}
initAnotherFunction: function() {
//More code
}
}
(It would be helpful if someone can tell me what this method is called so that I can research it more.)
My problem arises when I try to do the same thing in my node app in the home directory /main.js. The node app works fine on its own but when I add something like this:
test2 = {
initMyFunction: function() {
console.log("I finally decided to work! Good luck...");
}
}
and modify my html file like this:
<script src="../../main.js"></script>
<script type="text/javascript">
$(document).ready(function(){
test.initSomeFunction();
test2.initMyFunction();
});
</script>
then it won't work. Can someone please point me to the right direction as I don't even know what to Google. I am trying to avoid using RequireJS or anything else as I am a total beginner and the method that the developer used sounds so simple and tempting.
I wish this answer will help you:
I am using express, so I do this to solved your problem!
main.js file's position:
modify app.js add:
app.use(express.static(path.join(__dirname, '/')));
Then, in the view file:
<html>
<head>
<script src="public/javascripts/jquery-1.10.2.min.js"> </script>
<script src="main.js"></script>
</head>
<body>
<script>
$(function () {
//test.initSomeFunction();
test2.initMyFunction();
})
</script>
</body>
</html>
Open the chrome Developer Tools. You will see the result.

React component rendering on server-side, but client-side does not take over

I have an EJS view which is served up to a client:
index.ejs
<!DOCTYPE html>
<html>
<head>
<title>Example app</title>
</head>
<body>
<div id="reactApp">
<%- reactContent %>
</div>
</body>
<script src="__res__/client/main.bundle.js" />
</html>
main.bundle.js is the bundle that I create using browserify:
gulpfile.js (partial)
function bundle(filename) {
var bundler = browserify('./app/client/' + filename + '.js');
bundler.transform(babelify);
bundler.transform(reactify);
return bundler.bundle()
.pipe(source(filename + '.bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./dist/client'));
}
And the client is ultimately served this code:
main.js (bundled into main.bundle.js)
import React from 'react';
import {Login} from './auth/login.react';
React.render(React.createElement(Login), document.getElementById('reactApp'));
alert('hi');
However, even though the browser requests and recieves the main.bundle.js script, the client does not run the alert('hi'); line, which leads me to believe that the React.render line does not work either. I can affirm that Javascript is enabled, and my browser is the latest version of Chrome. My react component (Login) is as follows:
login.react.js
import React from 'react';
export class Login extends React.Component
{
handleClick() {
alert('Hello!');
}
render() {
console.log('rendered');
return (
<button onClick={this.handleClick}>This is a React component</button>
);
}
}
So, very simple. However, none of the alerts that you see in the code is ever run. The console.log('rendered'); line is never run on the server, but when I check the source code for my page, I get:
HTML output of my page
<!DOCTYPE html>
<html>
<head>
<title>Example app</title>
</head>
<body>
<div id="reactApp">
<button data-reactid=".2fqdv331erk" data-react-checksum="436409093">Lel fuck u</button>
</div>
</body>
<script src="__res__/client/main.bundle.js" />
</html>
Which means that the server correctly renders my react component, but why does the client script not work? The handleClick function never runs, my console.log lines never run, and neither does the alert lines. What is happening? The reactid and checksum are rendered correctly, shouldn't it be working? Shouldn't the React code on the client-side be smart enough to find the component and run correctly?
In your index.ejs, adding a closing element to your script tag should fix the issue: <script src="__res__/client/main.bundle.js"></script>
On a separate note, in my testing, I was getting an error in login.react.js when loading the page until I added default to the export line: export default class Login extends React.Component. Not sure if you will need to do the same.

Categories

Resources