Search code examples
jquerypythonpostrequestpyramid

Getting a key error on the object I'm sending to the server (jQuery -> Python)


Below is the login object I'm sending to the server:

Object {username: "[email protected]", password: "password"} 

It contains an invalid username and password.

Here in the python it checks the POST, and then checks the username

try:
        print self.request.POST
        username = str(self.request.POST['username'])

The Print returns the following:

MultiDict([('{"username":"[email protected]","password":"password"}', '******')])

However it errors out on the username = line

The exception block:

except Exception, ex:
        print ex.message

The exception is ex = {KeyError}'username'

Any thoughts as to why username = str(self.request.POST['username']) is not fetching the username from the POST?


The HTML form (action removed because I can't show error messages otherwise)

<!-- LOGIN -->
<div id="login-form">
    <form class="login-form" action="" method="post">

    <input type="text"
        id="login-email" value="email" name="username"
        onblur="if (this.value == '') {this.value = 'email';}"
        onfocus="if (this.value == 'email') {this.value = '';}"
        autocomplete="off"/>

    <div class="tip-error-message" id="error-email"><span>A valid email is required</span></div>

    <input type="password"
        id="login-password" value="password" name="password"
        onblur="if (this.value == '') {this.value = 'password';}"
        onfocus="if (this.value == 'password') {this.value = '';}"
        autocomplete="off"/>

        <button id="login_page_submit" type="submit">login</button>

    <div id="login-form-background"></div>
    </form>
</div>

Then in the jQuery I have this, so when I get an error response back I can display the message on the page:

$('#login-form').unbind('submit').bind("submit", function(event) {

 WHOAT.validation.validateLoginForm('#login-form'); // custom validation

     var params = {
        username : '',
        password : ''
     }

    params.username = $('#login-email').val();
    params.password = $('#login-password').val();

    console.log(params.username); // [email protected] 
    console.log(params.password); // password

    WHOAT.networking.postToServerWithAjax('/login', params, function (response) {

        console.log(response);

    });

       return false;

});

the postToServerWithAjax function

var postToServerWithAjax = function (url, params, callback) {
    console.log('postToServerWithAjax:');
    console.log(url);    //returns: login 
    console.log(params); //returns: Object {username: "[email protected]", password: "password"} 
    invokeServer(url, params, callback, 'POST');
}

the invokeServer function

var invokeServer = function(url, params, callback, postMethod) {
    WHOAT.analytics.trackPageView(url);
    $.ajax({
        type: postMethod,
        url: url,
        cache: false,
        data: JSON.stringify(params),
        //contentType: 'charset=utf-8',
        statusCode: {
            200: function (data, textStatus, jqXHR) {
                callback(data);
            },
            201: function (data, textStatus, jqXHR) {
                callback(data);
            },
            400: function (data, textStatus, jqXHR) {
                callback(data);
            }
        }
    });
}

Solution

  • You are posting JSON-encoded data, not form-encoded or URL-encoded data.

    Access the JSON-encoded object with the requests.json_body attribute:

    username = self.request.json_body['username']