Skip to main content
2 of 2
edited body
Saif Bechan
  • 294
  • 1
  • 5
  • 14

How to exactly work with the JSON Object and jQuery, adding info to posts

I have been working with AJAX and JSON for quite some years now, but to be honest I still do not know exactly what all the functionality are, and how to create optimized code for jQuery.

So my first question: Does anyone know a good tutorial, or better even a cheatsheet where are the functionalities are explained. I have Googled and looked at the normal jQuery documentation for years now, but I still can't manage to think in optimized paterns, if that makes any sense at all.

Now to illustrate this with a relevant problem. Currently I am developing a small public plugin that adds various counters to posts, nothing special here.

<ul id="container-60">
  <li class="counter-x">&nbsp;</li>
  <li class="counter-y">&nbsp;</li>
  <li class="counter-z">&nbsp;</li>
</ul>

<ul id="count-container-64">
  <li class="counter-x">&nbsp;</li>
  <li class="counter-y">&nbsp;</li>
  <li class="counter-z">&nbsp;</li>
</ul>

Now this has to be filled. The best way I could make this work is with the following json sting:

{ "posts" : 
    { "60" : 
        { "x" : "100", "y" : "200" , "z" : "300" }
    },
    { "64" : 
        { "x" : "400", "y" : "500" , "z" : "560" }
    }
}

Now as for the ajax there is a double loop:

    // AJAX blah blah blah above
success : function( data ){
    posts = data.posts;
    jQuery.each( posts, function( post_id, post_counts ) {
        jQuery.each( post_counts, function( item_name, item_count ) {
            jQuery( '#container-' + post_id + ' .counter-' + item_name ).text( item_count );
        });
    });
}

Now this works fine, but I bet there is a better way for doing this. Maybe change the json string to a more optimized version for doing things quicker.

jQuery has so many special functions.

Anyone have any suggestions.

Saif Bechan
  • 294
  • 1
  • 5
  • 14