1

I have a function on my page that uses ajax. The ajax goes to a Django view, which can then return some sort of data for me. Unfortunately, I can only get it to return one piece of data at the moment. The second gets returned as the string "success". Here's what I have going:

Ajax:

 success: function(data, message) { 
            if(data === 'False'){
                    $('#mailsquare').css('background-color', '#A80000');
                    $('.dropdown-menu').prepend('<li class="message" id="{{item.id}}">'+message.substring(0,30)+'</li>');
            } else {
                    $('#mailsquare').css('background-color', '#1b1b1b');
            }
   },

View:

@login_required
def checkMail(request):

    user = request.user.get_profile()

    i = inbox.objects.get(user = user)
    read = i.read

    new = i.message.order_by('created')[:1]

    return HttpResponse(read, new)

The prepend statement doesn't use the "message" value that it is receiving, but rather just inserts the string "success". The "data" parameter is handled correctly.

2 Answers 2

4

The success method is defined like this:

success: function(data, textStatus, jqXHR) { 

So, message is actually the textStatus Hence the result.

You need to send the data from the view correctly for this to work correctly.

One way to do it is:

@login_required
def checkMail(request):
    user = request.user.get_profile()
    read = inbox.objects.get(user = user).read    
    newest = i.message.order_by('created')[:1]

    return HttpResponse(simplejson.dumps({'read': read, 'newest': newest}))

and in the js

success: function(data, textStatus, jqXHR) { 
    var read = data.read;
    var newest = data.newest;
    //rest of the stuff    
}
Sign up to request clarification or add additional context in comments.

2 Comments

It's JsonResponse (instead HttpResponse) nowadays.
Simply do: data = {'read': read, 'newest': newest} And then: return JsonResponse(data)
0

You wrong return the data for ajax

def answer(request):    
     # same you code
     payload = {'success':True,'param1': 'you_value', 'param2':'you_value2'}
     return HttpResponse(json.dumps(payload), content_type='application/json')

In Javascript

success: function(data) { 
        if(data.success === false){
                alert(data.param1);
                alert(data.param2);

        } else {
                $('#mailsquare').css('background-color', data.param1);
                $('#mailsquare').html(data.param2);
        }},

Comments

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.