"Ajax support"

This commit is contained in:
Doug Le Tough 2017-11-26 00:05:35 +01:00
parent 4ff95ba727
commit 84d9a0664e
5 changed files with 229 additions and 2 deletions

View File

@ -0,0 +1,144 @@
var red = "#FF0000";
var green = "#00FF00";
var light_red = "#FCD5DC";
var light_green = "#D5FCD8";
var base_bg = "#FFFFFF";
var base_border = "#888888";
/* **************************************************************************************
* GLOBAL
* **************************************************************************************/
// Cookies
function setcookie(cname, cvalue, exdays) {
// Set cookie
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getcookie(cname) {
// Get cookie by name
var value = "; " + document.cookie;
var parts = value.split("; " + cname + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
// Eye candies
function invalid_input(obj) {
// Invalid input makes obj borders and background to glow red for 2 seconds
// Border color will stay red until a valid input is sent
obj.style.backgroundColor = light_red;
obj.style.borderColor = red;
setTimeout( function() {
obj.style.backgroundColor = base_bg;
}
, 2000);
}
function valid_input(obj) {
// Valid input makes obj background to glow green for 2 seconds
// If obj borders were red, they get they normal color back
obj.style.backgroundColor = light_green;
obj.style.borderColor = base_border;
setTimeout( function() {
obj.style.backgroundColor = base_bg;
}
, 2000);
}
/* **************************************************************************************
* AJAX
* **************************************************************************************/
function get_html_from_ajax(obj, url) {
// Get HTML content from AJAX request from url argument
// HTML content is then put as innerHTML to obj
var xhttp = new XMLHttpRequest();
xhttp.onerror = function(){
obj.innerHTML = "Erreur lors de la récuperation du contenu (1)";
};
xhttp.onload = function(){
if (xhttp.status != 200) {
obj.innerHTML = "Erreur lors de la récuperation du contenu (2)";
}
};
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var response = xhttp.responseText;
obj.innerHTML = response;
}
};
xhttp.open('POST', url, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send();
}
function set_value_from_ajax(obj, url, err_code) {
// Send value from obj.value via AJAX request to url argument
// obj.value is passed to URL in a REST sheme like <URL>/<VALUE>
// If err_code response is received, then a server side
// error has occured and input is invalidated.
url = url + '/' + obj.value;
var xhttp = new XMLHttpRequest();
xhttp.onerror = function(){
invalid_input(obj);
};
xhttp.onload = function(){
if (xhttp.status != 200) {
invalid_input(obj);
}
};
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var response = xhttp.responseText;
if (response == err_code) {
invalid_input(obj);
return;
}
valid_input(obj);
return;
}
};
xhttp.open('POST', url, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send();
}
function get_value_from_ajax(obj, url, err_code) {
// Get value from AJAX request
// The returned value is then set to obj.value.
// If err_code response is received, then a server side
// error has occured and input is invalidated
var xhttp = new XMLHttpRequest();
xhttp.onerror = function(){
invalid_input(obj);
};
xhttp.onload = function(){
if (xhttp.status != 200) {
invalid_input(obj);
}
};
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var response = xhttp.responseText;
if (response == err_code) {
invalid_input(obj);
return;
}
obj.value = response;
valid_input(obj);
return;
}
};
xhttp.open('POST', url, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send();
}

View File

@ -0,0 +1,25 @@
{% extends "index.html" %}
{% block main %}
<article class='left'>
<h3>Get HTML response from AJAX</h3>
<p>Click the refresh button to get the HTML response.</p>
<p>The response may randomly be an error response.</p>
<input type='button' class='refresh' value=' ' onclick='javascript:get_html_from_ajax(document.getElementById("html_container"), "/get_html_from_ajax");'>
</article>
<article class='right' id='html_container'>
</article>
<article class='left'>
<h3>Set value via AJAX</h3>
<p>Send value to the application.</p>
<p>If value is empty or is "We Make Porn" (case sensitive), an error is raised.</p>
<input type='text' id='value_sender'>
<input type='button' value="Try me" onclick='javascript:set_value_from_ajax(document.getElementById("value_sender"), "/set_value_from_ajax", "TETA_ERR");'>
</article>
<article class='left'>
<h3>Get value from AJAX</h3>
<p>Get a random value from the application.</p>
<p>Value may randomly be unavailable raising an error.</p>
<input type='text' id='value_receiver'>
<input type='button' value="Try me" onclick='javascript:get_value_from_ajax(document.getElementById("value_receiver"), "/get_value_from_ajax", "TETA_ERR");'>
</article>
{% endblock %}

View File

@ -0,0 +1,24 @@
<h3>This is the title</h3>
<img src='/static/images/dummy_pic.png' alt='dummy pic' title='dummy pic'/>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore
</p>
<p>This <a href='/plop.html'>link</a> will lead to an error page</p>
<p>
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia desers unt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
</p>

View File

@ -6,7 +6,7 @@
<li><strike>Basic menu management</strike></li>
<li>Installation wizard</li>
<li>Back office for basic content management</li>
<li>Basic Ajax support</li>
<li><strike>Basic Ajax support</strike></li>
<li>Session management</li>
<li>Basic documentation</li>
<li>Horizontal navbar</li>

View File

@ -42,6 +42,7 @@ def get_menu(page):
['Articles', '/articles', 0],
['Basics', '/basics', 0],
['Inputs', '/inputs', 0],
['Ajax', '/ajax', 0],
['Database', '/database', 0],
['Todo', '/todo', 0],
]
@ -69,7 +70,7 @@ def get_menu(page):
@app.errorhandler(404)
def page_not_found(e):
""" 404 not found """
return render_template('error.html', menu=app.menu), 404
return render_template('error.html'), 404
@app.route("/", methods=['GET', 'POST'])
@ -97,6 +98,12 @@ def inputs():
menu = get_menu(page)
return render_template('inputs.html', menu=menu)
@app.route("/ajax", methods=['GET', 'POST'])
def ajax():
page = inspect.currentframe().f_code.co_name
menu = get_menu(page)
return render_template('ajax.html', menu=menu)
@app.route("/database", methods=['GET', 'POST'])
def database():
page = inspect.currentframe().f_code.co_name
@ -109,7 +116,34 @@ def todo():
menu = get_menu(page)
return render_template('todo.html', menu=menu)
########################################################################
# AJAX
########################################################################
@app.route("/get_html_from_ajax", methods=['GET', 'POST'])
def get_html_from_ajax():
import random
if int(random.random()*10) % 2:
# Randomlu generate 404 HTTP response
return render_template('error.html'), 404
return render_template('ajax_html.html')
@app.route("/get_value_from_ajax", methods=['GET', 'POST'])
def get_value_from_ajax():
err_code = 'TETA_ERR'
import random
RND = int(random.random()*10)
if RND % 2:
# Randomlu generate error
return err_code
return str(RND)
@app.route("/set_value_from_ajax/<value>", methods=['GET', 'POST'])
def set_value_from_ajax(value):
err_code = 'TETA_ERR'
if value != 'We Make Porn':
return 'True'
return err_code
########################################################################
# Main