Reputation: 589
script.js
$('#loginform').submit(function(e){
$.ajax({
type:"POST",
url:"/accounts/login/ajax/",
data:$('#loginform').serialize(),
success: function(msg){
var msg = msg;
msg = JSON.parse(msg);
$('#messagestatus').html('');
if(msg.username != null){
$('#messagestatus').append(msg.username);
}
if(msg.password != null){
$('#messagestatus').append(msg.password);
}
}
});
e.preventDefault();
});
returned object
{'username':['Required'],'password':['Required']}
When I am using JSON.parse
and I am alerting, it's showing the correct error, but when I am appending it to the messagestatus
div its not responding, please help .
Upvotes: 0
Views: 88
Reputation: 1062
First of all, parameters do not need to be redeclared in their function.
then, to parse your json using $.parseJSON() :
msg = $.parseJSON(msg);
Your JSON contains arrays, use msg["username"][0] to access the first string and not the full array.
And I would put e.preventDefault(); as first statement before AJAX.
And .html('') => .empty() but it's the same result.
Upvotes: 0
Reputation: 360912
Might be significant, might not be, but your json object actually consists of sub-arrays:
{'username':['Required'],'password':['Required']}
^----------^ ^----------^
meaning that the decoded data structure in JS would actually be
obj['username'][0] and obj['password'][0]
Upvotes: 1
Reputation: 2565
Your username and password are arrays in your json.Either make it that your json looks like
{'username':'Required','password':'Required'}
or change your script:
if(msg.username.length > 0)
{
$('#messagestatus').text(msg.username[0]);
}
if(msg.password.length > 0)
{
$('#messagestatus').text(msg.password[0]);
}
Upvotes: 2