deelaws
deelaws

Reputation: 134

Data not sent using jquery .ajax() to a Django view

I am trying to create a single ajax call. The ajax call is sent to server but the data then I am sending is not available in the request object in the view. When I print request.post, it gives <QueryDict: {}>. No data is being sent to the server. I know that the browser is sending the data since I can view it in the request payload in chrome.

script:

$("#chatform").submit(function(e) {
    e.preventDefault();
    //serialText = $(this).serialize();
    var userText = $("#usertext").val();
    var xmlRequest = $.ajax({
            type: "POST",
            url: "/sendmessage/",
            data: {'tosend': userText},

            //dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function(data){
                appendMessageSent(data.messagesent);
            }
    });
});

view.py:

def send_message(request):
    if request.is_ajax():
        message = "The hell with the world"

        print request.POST
        json = simplejson.dumps(
            {'messagesent' : request.POST['tosend']+"This is how we do it"}
        )
        return HttpResponse(json, mimetype='application/javascript')

html

<form id="chatform" action="" method="POST" >
        <input type='hidden' name='csrfmiddlewaretoken' value='8idtqZb4Ovy6eshUtrAiYwtUBboW0PpZ' />
        <input type="text" name="chatarea" id="usertext"/>
        <input type="submit" value="Send">
</form>

I get an error saying that key tosend is not found in request.post dict.

MultiValueDictKeyError: "Key 'tosend' not found in <QueryDict: {}>

Can any one tell me why the data is not being sent to the server and/or why I can't access it in my view?

Upvotes: 2

Views: 2931

Answers (1)

Pavel Anossov
Pavel Anossov

Reputation: 62948

To make form data appear in request.POST, use contentType: "application/x-www-form-urlencoded".

If you use application/json, you have to parse the raw data yourself (request.raw_post_data in django <1.4, request.body in django >=1.4):

def send_message(request):
    if request.is_ajax():
        message = "The hell with the world"

        data = json.loads(request.body)
        result = json.dumps({'messagesent' : data['tosend'] + "This is how we do it"})
        return HttpResponse(result, mimetype='application/javascript')

Upvotes: 7

Related Questions