Python Flask: Return HTML Content - javascript

i am trying to put together a makeshift tool for my own personal use, im not experienced with backend development at all. so my methods may be unconventional. although there may be a much better method to go about this
consider the following snippet from my html file:
<tr><td>
<button id="socks.shirt.pants"> dummy text here </button>
</td></tr>
my goal, as simply as i can put it, is to click BUTTON and return the string text within the ID attribute in python using Flask. Below is the code i am working with.
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
#display html file
return send_from_directory('','myfile.html')
#this is the part that needs help
textdata = request.htmlcontent.td.id
i have tried several different ways to extract the html content. including but not limited to:
request.html.tr.id,
request.get_data(),
request.data(),
request.form,
i understand now that request.form returns user-supplied information submitted in a form, which wont work for me because the information that i want to retrieve will be hardcoded into the html file under whichever tag that would allow this process to work. (currently tr -> td -> button).
the other methods either returned None or an some empty string, i believe.
also, i am wondering if maybe there is some piece of javascript code that ill need to use in addition to Flask as well? i hope that this is not an unrealistic expectation to ask this question! any suggestions would help greatly!

You can use ajax with jquery:
In the main filename.py, include a route like this, that access the parameters from the json response from the frontend. Also, provide a route that will render the HTML template:
#app.route('/recieve_data')
def get_id():
the_id = flask.request.args.get('button_id')
return "<p>Got it!</p>"
#app.route('/', methods=['GET', 'POST'])
def home():
return flask.render_template('filename.html')
In your HTML (stored in filename.html), utilize the code below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<tr><td>
<button id="socks.shirt.pants" type='button'> dummy text here</button>
<div id='response'></div>
</td></tr>
</body>
<script>
$(document).ready(function() {
$("button").click(function(event){
var the_id = event.target.id;
$.ajax({
url: "/recieve_data",
type: "get",
data: {button_id: the_id},
success: function(response) {
$("#response").html(response);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>

Related

using ajax in flask to load live logs

I am looking for some help, regarding my web server. I have a flask web server, designed to search in log files, and it does the job, but I need something else. To access the live data, to see the logs live.
It's an internal application, so the security is not a concern. The main thing it should do, is to open a file and basically simulate a "tail" command.Read the last lines, then just append the new ones, and basically that's all.
I was thinking to go with an AJAX call, but i'm not really good (at all) with JavaScript.
I was wondering about this solution :
var byteRead=0;
setInterval(function(){
$.ajax({
type: "GET",
url: "GenNumber.txt",
dataType: "text",
success: function (data) {
byteRead+= data.length;
readdata(data);
},
headers: {
"Range" : "bytes="+byteRead+"-"
}
});
},1000);
But im not quiet sure about it... neither how to adapt it (js side).
Does anyone have experience with this kind of issues or ideea how to start ?
So, in short terms in case of anyone else needs something like this, the solutin is :
#login_required
def live():
return render_template('live.html',user=current_user)
#views.route('/live_logs', methods=['GET', 'POST'])
def live_logs():
if request.method == 'GET':
def generate():
var_live = ''
var = sp.Popen(['tail','-f',var_live],stdout=sp.PIPE,stderr=sp.PIPE)
while True:
var_live_log = var.stdout.readline()
var_live_log = var_live_log.decode('utf-8')
yield "data:" + str(var_live_log) + "\n\n"
time.sleep(0.1)
return Response(generate(), mimetype= 'text/event-stream')
And the HTML file should look like this :
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<br>
<hr>
<section class="section">
<div class="livelog">
<div class="columns is-centered is-mobile">
<div class="column is-dark notification is-four-fifths">
<div class="is-size-7 has-text-warning" id="display">
<ul id="display_list" class="logs"></ul>
</div>
</div>
</div>
</div>
</section>
</body>
</html>
{% endblock %}
Obviously this may differ, based on base.html
But this code will create a tail session which and stream it to the browser, also can be modified to read a file or smth..

Onclick write to database whithout refreshing

I've been working on a Flask application for a while.
Everything going pretty smooth because I was avoiding a problem. When writing to the database I always used a post ( that makes the page reloading ).
Not a big problem when posting forms etc.
Now I want a "i want help" button that makes a value true or false in the db.
Based on this value i would generate html that provides help.
But the button cannot make the page refresh. This is where i got stuck.
I only managed to get it working without writing to the db ( and storing it localy ).
Is there an obvious thing that i miss? or some Flask magic that gets it done.
The solution that I'm thinking about is posting to the db after leaving the page. Haven't got this working though.
Thanks in advance!
This example uses Ajax to send some data to the Flask back-end with jQuery and receive a response. It's very simple, but I marked the place where you'd handle the processing that you want the back-end to take care of after the user clicks your help button.
from flask import Flask, render_template_string, request
app = Flask(__name__)
#app.route('/')
def index():
return render_template_string('''
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#send_data').on('click', function() {
$.ajax({
url: "{{ url_for('data_post') }}",
method: "POST",
data: {
data: $('#data').val()
},
success: function(data) {
$('#response').html(data);
}
});
});
});
</script>
</head>
<body>
<input type="text" name="" id="data">
<button id="send_data">Send</button>
<br />
<p id="response"></p>
</body>
</html>
''')
#app.route('/data', methods=['POST'])
def data_post():
# handle your database access, etc.
return 'received'
if __name__ == '__main__':
app.run()
It's a simple index page with a textbox and button. Enter something into the textbox and click the button. You should see "received" on the page underneath the makeshift form, which is the echo from the back-end that the processing (in this example there isn't any) is done.
I'm also working on a Flask app currently, if you don't want to reload the webpage, you'll have to make an AJAX call. This can be easily done via jQuery.post() function. Also, you might need to setup a new route in Flask, so as to provide the required data to which the post function will make a request. To disable auto form submission, you can use:
$('form').submit(false);
And for posting manually and receiving data from server, you can use:
<button ... onclick="submitForm()">Submit</button>
And submitForm():
function submitForm()
{
$.post( url, { "data": "form-data" }).done(function (){...});
}
Hope this helps.

Python-Flask AJAX GET data does not display on HTML page

I have created a single page app using Python and Flask. The page has a "next" button. When the user clicks the "next" button I want to reload the page using data ('id2') that I send with the GET request.
Here's my problem: When I execute the GET request I can see that the AJAX data is being received by my Python controller function. But, the HTML page does not seem to refresh with the correct data (In the example below, "bar" is not passed to the HTML page.)
I believe that no new page is being sent to my browser. The output in my terminal window below only shows a GET request. Also, when I look at the network traffic in Chrome Dev tools, after I click the 'next' button, I only see a new get request, and no new page is sent to the browser.
Can someone please help me understand how to create a GET (or POST) request that triggers the server to serve a new HTML page that includes the data from the GET request?
Thanks!
My Python Controller:
#app.route('/', methods=["GET", "POST"])
def home_page():
print 'new page requested'
data = request.args.get('id2');
if data != None:
return render_template("index.html", article="foo")
else:
return render_template("index.html", article="bar")
My HTML/Javascript code:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<p>{{ article }}</p>
<button class="next" id="next">Next</button>
<script>
$("#next").click(function() {
$.ajax({
type: "GET",
url: '/',
data: {id2: "{{ article }}"}
});
});
</script>
</body>
Terminal Data:
new page requested
127.0.0.1 - - [17/Apr/2015 00:01:16] "GET /?id2=foo HTTP/1.1" 200 -
If you want to use AJAX to replace the entire DOM with the template being output from your Flask app you can simply do the following:
var nextArticle == 'foo';
$("#next").click(function() {
$.get("/?id2=" + foo, function(data) {
document.open('text/html');
document.write(data);
document.close();
// recreate binding for your $("#next") button
}
}

Use AJAX to send html5 textarea directly without html <form>

Recently I am confused about whether it's possible to send input/textarea data directly without being included in html <form>. I thought in web page, if we want to get information from user then send the text to authentication server, we must use <form> irrespective of in which way it's submitted.
But an anonymous reviewer of my paper claims that <html> can be bypassed by using an html5 tag "textarea" and JS AJAX post. While I did lots of experiments trying to implement his way but all failed.
I wonder if there is really some way to submit user info without using <form> tag?
Thank you
Thanks for everyone's reply.
Update: I followed "the_void"'s code and changed the url of AJAX to a ServerSocket (implemented by Java). The server was able to get the POST event, but it cannot read the "data" of AJAX. The following is the html code:
HTML
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
// information to be sent to the server
info = $('#foo').val();
$.ajax({
type: 'POST',
url: 'http://10.0.0.3:8888',
data: ({ foo: info }),
// crossDomain: true,
// dataType: 'json'
});
return false;
});
});
</script>
</head>
<body>
<label>Text</label>
<textarea id="foo"></textarea>
<button id="submit">Submit via Ajax</button>
</body>
</html>
It seems that the socket server cannot read from AJAX (but it can read from < form > + < action >). Is there any way to fix the reading issue?
Thank you
Ajax (Asynchronous Javascript & XML) is a way to send data from client to the server asynchronously. For that you'd have to write code for sending the data in the client-side using Javascript/HTML and also to process the received data using server-side languages (eg PHP) on the server-side.
And, yes you don't need a <form> tag to do so.
Check out this example.
HTML:
<label>Text</label>
<textarea id="foo"></textarea>
<button id="submit">Submit via Ajax</button>
Javascript:
$('#submit').click(function(e) {
e.preventDefault();
// information to be sent to the server
var info = $('#foo').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {foo: info}
});
});
Server-side Handler (PHP): server.php
<?php
// information received from the client
$recievedInfo = $_POST['foo'];
// do something with this information
See this for your reference http://api.jquery.com/jquery.ajax/
Perhaps your reviewer was referring to the HTML5 textarea attribute "form". It allows a textarea to be part of a specified form without being inside the form element.
http://www.w3schools.com/tags/att_textarea_form.asp
But generally speaking, as long as you can identify an element, say a textarea, you can access the text inside it and send it to the server without submitting any forms using ajax.
From Sable's comment:
http://api.jquery.com/jquery.post
OR
http://api.jquery.com/jquery.ajax/
Yes, you can submit data to a server without putting it into a form. Form's provide a simpler mechanism for sending larger amounts of data to a server without the developer having to tell the browser how to encode the form.
EG:
HTML
JS
var text = $("input[type='text']").val();
$.post("/my/server/url", { userInput : text }, function(data){ /* Success! */});
This would technically post the data to the server without a form.

How to load a url in html div and post data through http post method?

I have written a html page, and I wrote following code where I am using Jquery to load a specific url inside a html div :
<html>
<head>
<title>forms</title>
<%
String outputLink = ServerSupportUtil.getAttributeStringValue(request,"outputlink");
String secParam = ServerSupportUtil.getAttributeStringValue(request,"secparam");
%>
<script src="../common/jquery-1.6.2.min.js"></script>
<script>
$(document).ready(function(){
$("#menu").html('<object data="<%=outputlink%>">').appendTo('body');;
});
</script>
</head>
<body>
<div id="menu" style="position:relative; bottom: 0; overflow:hidden;">
</div>
</body>
</html>
Above code is working good.
Now I also want to send a specific parameter named as secParam(which I get from request object) through http post along with this url so that server can do authentication.
So how should I load the same url in the div by doing http post request?
Is this possible using Jquery ?
First create an simple container to display whats retuned. Then use jquery $.post() method :
//Empty container div
<div id="container"></div>
$.post('ajax/test.html', { secParam: "<%=secParam%>" }, function(data) {
$('#container').html(data);
});
I would recommend you not to use jsp scriptlets if that's what i see here.
String outputLink = ServerSupportUtil.getAttributeStringValue(request,"outputlink");
You have used a request method to request data(page) from server, so if you want to post the parameter to server used post method,you should change request to post, maybe cannot use the code above, you should create a html form and save your parameter in a hidden, and set the form action as the outputlink you request, you can get the parameter from the httpRequest.

Categories