Feeling a bit confused here. As a newcomer to JavaScript/jQuery, I decided to create a loop that would cycle through some JSON data:
<script type="text/javascript">
var geturl = "http://couponsforweed.com/?json=get_recent_posts";
$.ajax({
type:'GET',
url:geturl,
complete: function(){
},
success: function (data) {
var response = data; //JSON.parse(data);
// Success!
alert("status: " + response.status + "\ncount: " + response.count + "\npages: " + response.pages + "\ncount_total: " + response.count_total + "\nposts: " + response.posts.length);
//loop through posts
for(var i = 0; i != response.posts.length; i++) {
//get each element in the array
var post = response.posts[i];
// displaying results to see what's happening
output.innerHTML = i + " post: " + post.custom_fields.schemaState;
}
},
error:function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
</script>
The code seems to be working fine, and I'm proud of myself for making it work. However, there's one issue bothering me:
// Displaying results to see what's happening
output.innerHTML = i + " post: " + post.custom_fields.schemaState;
Why does this only show me the last result in the loop instead of all the results in a list?
Currently, I am getting:
9 Ca
What I'm aiming for is (each result in the loop):
1 Ca 2 Ca 3 Ca 4 Ca 5 Co 6 Wa 7 Co 8 Ca 9 Ca
In PHP loops within WordPress, you can iterate through all the fields of each post and retrieve the results accordingly. It seems a bit different in JavaScript.