views:

653

answers:

2

Hi,

I'm trying to convert a server side AJAX response script in to an Django HttpResponse, but apparently it's not working.

This is the server-side script

/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];

    /* RETURN VALUE */
    $arrayToJs = array();
    $arrayToJs[0] = $validateId;
    $arrayToJs[1] = $validateError;

if($validateValue =="Testuser"){        // validate??
    $arrayToJs[2] = "true";         // RETURN TRUE
    echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';          // RETURN ARRAY WITH success
}else{
    for($x=0;$x<1000000;$x++){
        if($x == 990000){
            $arrayToJs[2] = "false";
            echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';      // RETURN ARRAY WITH ERROR
        }
    }

}

And this is the converted code

def validate_user(request):
    if request.method == 'POST':
        vld_value = request.POST.get('validateValue')
        vld_id = request.POST.get('validateId')
        vld_error = request.POST.get('validateError')

        array_to_js = [vld_id, vld_error, False]

        if vld_value == "TestUser":
            array_to_js[2] = True
            x = simplejson.dumps(array_to_js)
            return HttpResponse(x)
        else:
            array_to_js[2] = False
            x = simplejson.dumps(array_to_js)
            error = 'Error'
            return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))
    return render_to_response('index.html',context_instance=RequestContext(request))

I'm using simplejson to encode the Python list (so it will return a json array).Coudn't figure out the problem yet.But I think that I did something wrong about the 'echo'. Anyway I'm expecting an good answer it will help me a lot.

Thanks.

+4  A: 

I usually use a dictionary, not a list to return json.

response_data['result'] = 'failed'
response_data['message'] = 'You messed up'
return HttpResponse(json.dumps(response_data), mimetype="application/json")
Tom
+1 for correct - not specifying the mimetype will get you into trouble
George
+4  A: 

I use this, it work fine.

from django.utils import simplejson

def some_view(request, records):
    result = []
    for record in records:
        result.append({"id":record.id, "name":record.name})
    return HttpResponse(simplejson.dumps(result), mimetype='application/json')
Dingo
The problem is here it's not getting the value from the input field vld_value = request.POST.get('validateValue')
MMRUser