Search code examples
pythonjqueryjquery-mobileflask

Jquery button click to send AJAX request with Flask and Python


I am trying to make a web application that accepts button clicks. The button clicked then sends a specific device, and operation code to the python application which then calls a irsend command using Lirc. This is based off of the source code/instructions from here:

https://github.com/slimjim777/web-irsend

http://randomtutor.blogspot.com/2013/01/web-based-ir-remote-on-raspberry-pi.html

The html for the button is simple and is in "Xbox.html"

<button onclick="clickedOp('Xbox', 'OnOff');"> Power </button>

This launches the js function:

<script>
function clickedOp(device_name, op) {
    $.ajax({url:'/' + device_name + '/clicked/' + op});
}

I know that the function is firing on a click event because if i put an alert command in the clickedOp function the alert command runs

the python/flask app looks like this:

from flask import Flask
from flask import render_template
from flask import request, redirect, url_for

BASE_URL = ''

app = Flask(__name__)


@app.route("/")
def menu():
    return render_template('menu.html')

@app.route("/<device_name>")
def remote(device_name):
    if device_name == "Xbox":
        return render_template('Xbox.html')


@app.route("/<device_name>/clicked/<op>")
def clicked(device_id=None, op=None):
    return render_template('test.html')

if __name__ == "__main__":
    app.run('0.0.0.0', port=80, debug=True)

All of the code up to the ajax request works. going to "/" loads the menu.html template and presents links to different devices, for instance

<a href="Xbox"> Xbox </a>

will route to

"/<device_name>" 

in the python program and "Xbox.html" is loaded. Then the button loads and clicking it fires the "clickedOp(device_name, op)" function. This is where it breaks down. Even though the ajax request routes to

"/<device_name>/clicked/<op>" 

the "test.html" page is not loaded

This is the case even though the Flask debugger says that there was a successful GET request(it returns 200) to "/Xbox/clicked/OnOff" (filling in the variables for the example above)

so any ideas why test.html is not being loaded from the ajax request, when it seems that in the source code/tutorial I provided he uses the same ajax method?


Solution

  • In the code the template will render and be returned to the jquery Ajax object, which will do nothing with it - it won't render it in the browser. Have you used your browser's developer tools to see if a response is received by the browser - again, if Flask logs HTTP 200 OK then I would imagine the request is being handled correctly. You should also be able to put print statements in your Flask method and see them logged too (I think).