How to access json return values in angular.js action success callback-Collection of common programming errors
I’m trying to make a post call using resources from angular.js and adding a success and error callback.
wbsModule.factory('gridData', function($resource) {
//define resource class
var root = {{ root.pk }};
var csrf = '{{ csrf_token }}';
return $resource('{% url getJSON4SlickGrid root.pk %}:wpID', {wpID:'@id'},{
get: {method:'GET', params:{root : root }, isArray:true},
update:{method:'POST', headers: {'X-CSRFToken' : csrf }},
});
});
I’m calling the update action like this:
args.item.$update([], successUpdateCallback, errorUpdateCallback);
where I followed this part of the docs:
non-GET instance actions: instance.$action([parameters], [success], [error])
The server returns json like this if an error occurs:
jsonReturn = [{'error' : "Oops.. a problem occured. We could not save your last change in the highlighted row: "}]
jsonReturn.append({'wp_id' : wp_id})
try:
for key, value in wpForm.errors.iteritems():
jsonReturn.append({"form_errors" : "
" + str(value)})
except Exception, e:
print e
return HttpResponse(json.dumps(jsonReturn, indent=4), mimetype="application/json", status=400)
For the error callback I am able access the error messages like this:
function errorUpdateCallback(result){
console.log(result.data);
error = result.data[0].error;
wp_id = result.data[1].wp_id;
form_errors = result.data[2].form_errors;
}
};
But when I try to do the same for the success function I’m getting this error, which is thrown before entering the successUpdateCallback:
'undefined' is not a function (evaluation 'a.push(U(b[c]))')
http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js
Where I create the json the same as in the error case at the server:
jsonReturn = [{'message' : "Successfull update."}]
return HttpResponse(json.dumps(jsonReturn, indent=4), mimetype="application/json", status=200)
and parsing the success callback the same as the error callback:
function successUpdateCallback(result){
console.log("in suc. update");
console.log(result);
message = result.data[0].message;
};
Whereas when I return an empty json object I do not get this error and the successUpdateCallback is entered, printing “in suc.update” to the console:
jsonReturn = []
return HttpResponse(json.dumps(jsonReturn, indent=4), mimetype="application/json", status=200)
-
For future reference:
Angular is expecting for a successful post call that the server responds with the json representation of the resource for which we called $update or $save.
I found it here. Hidden in a comment 🙂
card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'};
Therefore I’m returning the json representation of the resource from the server and it works as expected.