In the simple code snippet below, i am getting a JSON response from a php page and then trying to iterate it and alert out the name field on each JSON objects. But it doesnt alert out anything.
<html>
<head>
<title>AJAX DB</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id="name-submit">
<div id="formatted-data"></div>
<div id="name-data"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script >
$('input#name-submit').on('click',function(){
var name = $('input#name').val();
if($.trim(name) != ''){
$.post('appservice.php', {search_key: 'users_search', search_value: name}, function(data){
//$('div#name-data').text(search_data);
$.each(data, function(i, obj) {
alert(obj.name);
});
});
}
});
</script>
</body>
</html>
sample JSON
[
{
"id": 18927441,
"id_str": "18927441",
"name": "IGN",
"screen_name": "IGN",
"location": "San Francisco, CA"
}
]
console.log(data), is it astringor anobject? If it's a string, then you need to usedata = JSON.parse(data);to convert it from json to object first.dataTypeto .post, so jquery guess it based on return object, which would based on the return info from your php, and it seems jquery guess it'stext, so it didn't parse it for you, instead it gives you the raw content. Things would change if you passjsonas 4th param.