I think that it is a very basic question, but I have spent hours looking for an answer with no luck, I've the following json object (generated using play!Framework)
{
"preg.pregunta": [{
"message":"Debes escribir una pregunta",
"key":"preg.pregunta",
"variables":[]
}],
"preg":[{
"message": "validation.object",
"key":"preg",
"variables":[]
}]
}
This is my jquery piece of code
$.ajax({
type: $target.attr('method'),
data: dataString,
url:$target.attr('action'),
dataType: "json",
beforeSend: function() {
//some stuff
},
success:function(response){
//some stuff
},
error: function(response){
//I want to use the json response here.
}
});
I want to get all inside preg.pregunta (message and key values)
Any help?
UPDATED: well I don't have enough reputation to answer to myself, this is what I've found so far.
Ok maybe it would be more than obvious or I have to study a bit more; I found that jQuery doesn't parse properly a JSON response if it came along with a HTTP error (400 in this case).
someone knows why this behavior?
I just tested this code in success handler and works perfectly!
$.ajax({
type: $target.attr('method'),
data: dataString,
url:$target.attr('action'),
dataType: "json",
beforeSend: function() {
},
success:function(response){
//It is working perfectly!
$.each(response,function(object){ //first loop of the object
$.each(response[object],function(values){ //looping inside arrays
console.log(response[object][values].key) //getting value "key"
console.log(response[object][values].message) //getting value "message"
});
})
},
error: function(response){
//nothing happens here
}
});
UPDATED 2.
after searching about 2 hours, I've found a straightforward solution:
error: function(response){
//Note the jQuery.parseJSON function
var response = jQuery.parseJSON(response.responseText);
$.each(response,function(object){
$.each(response[object],function(values){
console.log(response[object][values].key)
console.log(response[object][values].message)
});
})
}
Explanation: when using error handler, jQuery returns a complex object describing the error, responseText contains the data retrieved from the server, so, you have to parse it using parseJSON function.
Hope this helps!