Starting to work on a project that is built completely on JSON data. It is returned like this:
{"location":{"id":10,"contactPhone":"8675309","contactName":"bob","name":"bill smith","zipCode":"90210","state":"California","address1":"104 S. Olive","city":"Temecula","country":"USA"},"success":true}
I am comfortable processing data returned in HTML form (usually tables) by traversing the DOM with the .find and other filtering to find success flags. I have no idea how to do this with JSON - I need to filter to the last object "success" and check if it is true or false. With HTML returned data I do it like this:
submitHandler: function(form) {
$.ajax({
//other ajax stuff
success: function(data) {
var answer = $(data).find("td:eq(1)").text();
var message = $(data).find("td:eq(3)").text();
//console.log(data);
if (answer == "True") {
$('#messages').show().html(message);
} else {
$('#messages').show().html('Error logging in: ' + message);
}
}
});
return false;
}
I am able to post to the webservice and get the returned JSON with this .ajax call
$.fn.serializeObject = function() {....}
submitHandler: function(form){
var wrapper = {};
var location = {};
wrapper.location = $("#newLocation").serializeObject();
$.ajax({
type: $(form).attr('method'),
url: '/web/service/' + 'locationService' + '/' + 'createLocation',
dataType: 'json',
async: false,
data: JSON.stringify(wrapper),
success: function(msg) {
console.log('success' + msg );
//need to traverse to success and if true, do something
},
error: function(msg) {
console.log('failure' + msg );
//need to traverse to success and if false, do something
}
});
return false;
}
How do you filter to the "success" part in a JSON string (string or object?)
What are the correct terms for the key/number pairs (is that even correct) in the JSON string IE "contactPhone":"8675309"
How do you then display the data if "success":"true" - I will work on that myself but if anyone has good method I would appreciate some advice. I would imagine you just appendTo a table somehow?
I have a lot of questions on JSON, and am trying to word the questions in a general manner so that the help I am given can help someone else, I apologize for the length of this post. I appreciate any help and if requested will shorten/edit this question.
msg here is a json formatted object. You can get success value like that:
success: function(msg) {
console.log('success' + msg.success );
if(msg.success) { //could be wrote: msg.success === true
//do some stuff
}
},
"contactPhone":"8675309"
contactPhone is the key, "8675309" is the value. But in your sample, to get "contactPhone" value, you need to first get the location object:
var contactPhoneValue = msg.location.contactPhone;