Adding Two Numbers using AJAX with a python script - python

I am trying to perform a very simple task here...adding two numbers entered on an HTML page. The result has to come from a python script . This has to be done using AJAX. SO I have created the following page with the javscript for ajax call as well:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var req = new XMLHttpRequest();
function askServer() {
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
var dataToSend = "?number1="+number1 + "&number2="+number2;
req.open("GET","myScript.py",dataToSend,true);
req.onreadystatechange = handleServerResponse;
req.send();
document.getElementById("result").innerHTML = "The request has been sent.";
}
function handleServerResponse() {
if((req.readyState == 4) && (req.status == 200)) {
var result = req.responseText;
document.getElementById("result").innerHTML = "The answer is : " + result + ".";
}
}
</script>
</head>
<body>
<p>Enter two numbers:
<input id="number1" type="number">
<input id="number2" type="number">
</p>
<p>To ask the server top add them, without refreshing the page, click this button: <button onclick="askServer()">Ask the Server</button></p>
</div>
<p id="result"></p>
</body>
</html>
I need some help with the python script. I know it would just require the two parameters in the query string ; add them and return.
Say I have created a .py file with the following statement
return "Hi".
The complete text "return 'HI!'" is returned as a result. I am just a python beginner.

This task can be simply done if you use a web framework.
Here is a huge list of Python web frameworks
https://wiki.python.org/moin/WebFrameworks
Using flask - http://flask.pocoo.org/
from flask import Flask, request
app = Flask(__name__)
#app.route('/myScript.py')
def view_add_numbers():
number_one = request.args.get('number1', '')
number_two = request.args.get('number2', '')
if number_one and number_two:
return '%s' % (int(number_one) + int(number_two))
else:
return 'Fail'
if __name__ == '__main__':
app.run()
You can create a better url and pass number1 and number2 in other way. Read the docs.

Related

How do I get the data from a html script tag into my python function?

I am trying to get the data that I have stored inside of a script tag in my html file to my python file so that I can use it in a python function, does anyone have any idea how I could achieve this? Here's my html code:
<textarea id="rendezook" class="rendezook"></textarea>
<button onclick="get_text();">Valider</button>
<script>
function get_text() {
var x = document.getElementById("rendezook")
location.href = "/validate_comment?rendezook=" + encodeURIComponent(x.value);
console.log(x.value)
}
</script>
And then this is my python file:
#app.route('/validate_comment')
def validate_comment(item_id=None):
print("test")
print(request.args.get("rendezook"))
print("test2")
return redirect(url_for('msr_edit', item_id=72))
test and test2 are not getting printed so it is not entering the function.
The easiest way is to just use a form that's submitted via a GET request:
<form action="/validate_comment">
<textarea name="rendezook" class="rendezook"></textarea>
<button type="submit">Valider</button>
</form>
This will result in an URL like /validate_comment?rendezook=some_value_here, so you can access it via request.args (as it looks like you're using Flask):
#app.route('/validate_comment')
def validate_comment():
print("yeet", request.args.get("rendezook"))
return redirect(url_for('msr_edit', item_id=72))
Based on comments, if you're unable to use a form for some reason, then:
<textarea id="rendezook" class="rendezook"></textarea>
<button onclick="test()">Valider</button>
<script>
function test() {
var x = document.getElementById("rendezook");
location.href = "/validate_comment?rendezook=" + encodeURIComponent(x.value);
}
</script>
EDIT 2
Here's a minimal example that provably works :)
from flask import request, Flask
app = Flask(__name__)
#app.route("/validate_comment")
def validate_comment(item_id=None):
x = request.args.get("rendezook")
return f"you said {x}"
#app.route("/")
def index():
return """
<textarea id="rendezook" class="rendezook"></textarea>
<button onclick="get_text();">Valider</button>
<script>
function get_text() {
var x = document.getElementById("rendezook")
location.href = "/validate_comment?rendezook=" + encodeURIComponent(x.value);
console.log(x.value)
}
</script>
"""
if __name__ == "__main__":
app.run()

How to correctly parse XML urls with requests in Python?

I would like to parse an XML file from a URL.
By doing the following:
req = requests.get('https://www.forbes.com/news_sitemap.xml')
Instead of getting the proper XML file, I get:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en_US">
<script type="text/javascript">
(function () {
function isValidUrl(toURL) {
// Regex taken from welcome ad.
return (toURL || '').match(/^(?:https?:?\/\/)?(?:[^.(){}\\\/]*)?\.?forbes\.com(?:\/|\?|$)/i);
}
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
function consentIsSet(message) {
console.log(message);
var result = JSON.parse(message.data);
if(result.message == "submit_preferences"){
var toURL = getUrlParameter("toURL");
if(!isValidUrl(toURL)){
toURL = "https://www.forbes.com/";
}
location.href=toURL;
}
}
var apiObject = {
PrivacyManagerAPI:
{
action: "getConsent",
timestamp: new Date().getTime(),
self: "forbes.com"
}
};
var json = JSON.stringify(apiObject);
window.top.postMessage(json,"*");
window.addEventListener("message", consentIsSet, false);
})();
</script>
</head>
<div id='teconsent'>
<script async="async" type="text/javascript" crossorigin src='//consent.truste.com/notice?domain=forbes.com&c=teconsent'></script>
</div>
<body>
</body>
</html>
Is there also a better way to handle the XML file (for example, if it is compressed, or by parsing it recursively if the file is too big...)? Thanks!
This site checks a cookie for GDPR if you give that cookie to request you can get XML file.
Try this code, works fine to me.
import requests
url = "https://www.forbes.com/news_sitemap.xml"
news_sitemap = requests.get(url, headers={"Cookie": "notice_gdpr_prefs=0,1,2:1a8b5228dd7ff0717196863a5d28ce6c"})
print(news_sitemap.text)
Using requests module I get the xml file. You can then use an xml parser library to do what you want.
import requests
url = "https://www.forbes.com/news_sitemap.xml"
x = requests.get(url)
print(x.text)

How to get file contents of a file automatically with AJAX?

I am using AJAX to get the contents of a file when I press a button(I am very new to AJAX.) , Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "data.dat", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">
<p>- - -</p>
</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
And here is the python to change the file(This is not the python code i am using, but it still does the same thing, almost):
from time import *
a = 0
while True:
print(a)
file = open("data.dat","w")
file.write("<p>"+str(a)+"</p>")
file.close()
sleep(1)
a+=1
I would like to get the file contents every second, How would I Do that? Any help is good.
You could use setInterval() to periodically run the function which updates your document.
var intervalID = setInterval(loadXMLDoc, 1000); // Every 1s

Ajax Reload Button

I am trying to put a simple python script (here I've used a random two-word generator which works fine) in a div on a webpage with Ajax and have a button beneath that reloads it. The page successfully loads the script... however, I haven't quite got my head around the missing part to call the script again to reload the random two words made by the python script (I understand why the code below is wrong but I can't work out how to make it right!). Pointer much appreciated!
(N.B. Yes I am using Python 2.4 because my web host hasn't upgraded yet - they will soon! And yes I saw this question but it didn't work for me...)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Find a sentence</title>
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<script>
$(function()
{
$.ajax({
url: "cgi-bin/test.py",
type: "GET",
data: {foo: 'bar', bar: 'foo'},
success: function(response){
$("#div").html(response);
}
});
});
</script>
</head>
<body>
<div id="div"></div>
<form name="input" action="cgi-bin/test.py" method="get">
<input type="submit" value="Regenerate!">
</form>
</body>
PYTHON:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgitb
cgitb.enable()
import linecache
from random import randrange
print "Content-Type: text/html"
print
# file length counter
def file_len(fname):
f = open(fname)
try:
for i, l in enumerate(f):
pass
finally:
f.close()
return i + 1
# range sizes
one_size = file_len('text/one.csv')
two_size = file_len('text/two.csv')
# random lines
one_line = randrange(one_size) + 1
two_line = randrange(two_size) + 1
# outputs
one_out = linecache.getline('text/one.csv', one_line)
two_out = linecache.getline('text/two.csv', two_line)
# output
sentence = one_out.strip('\n') + " " + two_out.strip('\n') + " "
print sentence
Well, I would assume that one has to click on the "Regenerate" button for the form to reload. My idea would be to have the ajax logic in a separate function. I don't think you need the form there since your reload call is now ajax call.
<head>
<script>
function reload() {
$.ajax({
url: "cgi-bin/test.py",
type: "GET",
data: {foo: 'bar', bar: 'foo'},
dataType : "html",
success: function(response){
$("#div").html(response);
}
});
}
$(window).load(function() {
reload();
$("#reload_button").click(function() {
reload();
});
});
</script>
</head>
<body>
<div id="div"></div>
<input type="button" id="reload_button" value="Regenerate!">
</body>

SL4A _R6 / Python4android_R4 webViewShow NullPointerException on simple example code

I'm trying to get a HTML Gui on my simple SL4A Python app. the only thing I need to perform is ask the user for 1 input string at the start of my app.
For debugging purposes I started of simple. Unfortunately even this won't function.
Any idea's what's wrong here? (I've tried several pieces of code like this and all have the same issue)
Python code:
import android
loop = True
droid = android.Android()
droid.webViewShow('/sdcard/sl4a/scripts/screen.html')
while loop:
res = droid.waitForEvent('data')
if res:
print str(res)
HTML code
<html>
<head>
<script>
var droid = new Android();
var fiets = function() {
droid.postEvent("data", document.getElementById("gsm").value);
}
</script>
</head>
<body onload:"fiets()">
<form onsubmit="fiets(); return false;">
<label for="say">What would you like to say?</label>
<input type="text" id="gsm" value="99999999" />
<input type="submit" value="Store" />
</form>
</body>
</html>
the error message is repeatedly (the number 3114 is incremental):
java.lang.NullPointerException
Result(id=3114, result=None, error=u'java.lang.NullPointerException')
update:
http://www.mithril.com.au/android/doc/EventFacade.html
As we go I read waitForEvent is deprecated in r4. I should use eventWaitFor instead.
This takes the error away but doesn't make the example function. Python script prints nothing.
update2:
droid.postEvent should become droid.eventPost
droid.waitForEvent('data') should become droid.waitForEvent('data')
In javascript and python.
Problem Solved

Categories

Resources