1

I'm doing a pretty simple thing here, making a POST request to Django from jQuery, and I'm getting a strange error for a pretty simple scenario. I have the following view function:

from django.views.generic.simple import direct_to_template as dto

def do_login(request):
    if request.method == "POST":
        return dto(request, "path/to/template.json", {
            'success': False,
            'cause': None
        }, mimetype="text/json")

Here's my template:

{ success : {{success|lower}}{% if cause %}, cause : {{cause}}{% endif %} }

...and here's my jQuery:

$.ajax("/login/", { type: "POST",
    data: $("#loginForm").serialize(),
    success: function(data) {
        console.log("login response: " + data);
    },
    error: function(data, stats, error) {
        console.log("login fault: " + data + ", " + 
                stats + ", " + error);
    }
});

Pretty simple, right? Here's what I get in the console:

login fault: [object Object], parsererror, SyntaxError: Unexpected token s

What's going wrong here? If I don't set the mimetype on my render method, then everything works fine. The problem is, I'd like to return JSON without having to force jQuery to reparse it. Can anyone spot my mistake here? I can't seem to see it.

2 Answers 2

2

The JSON is not valid. You need quotation marks around the identifiers, so "success" instead of success and "cause" instead of cause.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that fixed it. I didn't know this was required, as in JS { success: true } is the same as { 'success': true }.
1
from django.utils import simplejson as json

def do_login(request):
    if request.method == "POST":
        return HttpResponse(json.dumps({'success': False, 'cause': None}), content_type='application/json')

1 Comment

Super helpful, thanks. That makes things a little easier and means I don't have to write a template for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.