Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX Submission Form using Bottle (Python)

I'm having some issues getting AJAX communication working using the Bottle framework. This is my first time using AJAX, so it's likely I just have the basics wrong. Hopefully a Bottle/AJAX guru can point this novice in the right direction. Here is the code I'm using:

#!/usr/bin/env python

from bottle import route, request, run, get


# Form constructor route

@route('/form')
def construct_form():
    return '''

<html>
<head>
<script type="text/javascript">

    function loadXMLDoc()
    {
        xmlhttp = new XMLHTTPRequest();
        xmlhttp.onReadyStateChange = function()
        {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                document.getElementById("responseDiv").innerHTML = xmlhttp.responseText;
            }
        }

    xmlhttp.open("GET", "/ajax", true);
    xmlhttp.send();
    }   

</script>
</head>

<body>

    <form>
        <input name="username" type="text"/>
        <input type="button" value="Submit" onclick="loadXMLDoc()"/>
    </form>
    <div id="responseDiv">Change this text to what you type in the box above.</div>

</body>
</html> 

    '''

# Server response generator

@route('/ajax', method='GET')
def ajaxtest():
    inputname = request.forms.username
    if inputname:
        return 'You typed %s.' % (inputname)
    return "You didn't type anything."

run(host = 'localhost', port = '8080')
like image 837
patrickn Avatar asked Feb 06 '12 19:02

patrickn


1 Answers

There are a few issues here.

  1. Javascript is case sensitive. XMLHTTPRequest should be XMLHttpRequest. You should have seen an error about this in your Javascript console.
  2. onReadyStateChange should be onreadystatechange.
  3. If you fix the above two issues your AJAX call will work, but you will only ever get the 'You didn't type anything.' response. This is because you are using GET. You need to change your code so the form values are posted using the POST method.

Also, why aren't you using jQuery to do AJAX? It would make your life much easier. :)

like image 112
Alex Avatar answered Sep 20 '22 16:09

Alex