Search code examples
jqueryajaxmongodbpython-2.7bottle

jQuery ajax POST returning results in blank page


Expected Behaviour

01 - Form is posted using jQuery.
02 - Authorisation is processed.
03 - MongoDB query is performed.
04 - Results should be returned in place of form.

Actual Behaviour

Steps 1 - 3 complete, however step 4 doesn't; the correct results are being returned but in a blank page.

Form

<form name="login" id="login">
<p>username</p>
<p>password</p>
<input type="text" name="username" />
<input type="password" name="password" />
<button type="submit">login</button>
</form>

jQuery

<script>
$(document).ready(function() {
$('#login').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/login',
data: $(this).serialize(),
dataType: 'json',
success: function(results) {
$("#content_area").html("");
$("#content_area").append(results.content);
}
});
});
});
</script>

Python

@post('/login')
def login():
    """Authenticate users"""
    username = post_get('username')
    password = post_get('password')
    aaa.login(username, password, fail_redirect='/login')
    dbname = 'mydb'
    connection = pymongo.MongoClient(os.environ['OPENSHIFT_MONGODB_DB_URL'])
    db = connection[dbname]
    collection = db.myCollection
    href = 'my-title'
    query = {'title':href}
    projection = {'_id':0,'content':1}
    cursor = collection.find_one(query,projection)
    response.content_type = 'application/json'
    return dumps(cursor)

Solution

  • Solution:

    The contents of the login form page (ie the <form> not the html <head>) was loaded by getJSON().

    Long story short, I thought:

    What if the jQuery isn't loading properly because the content was loaded via getJSON()?

    So I changed the jQuery script to use .on ie:

    <script>
    $(document).on("submit","#login", function (e) {
    e.preventDefault();
    $.ajax({
    type: 'POST',
    url: '/login',
    data: $(this).serialize(),
    dataType: 'json',
    success: function(results) {
    $("#content_area").html("");
    $("#content_area").append(results.content);
    }
    });
    });
    </script>
    

    And now it loads correctly in the specified div.