Load data into table using JQuery and AJAX

Time for a small JQuery post, which I’m sure some people will find useful. Now, first off, I don’t use JQuery on a regularly basic – so some things might be done quicker/better. I can only say that it works for me 🙂

The code presented will be using JQuery 1.7.2, but should also work with 1.8.x!

This example will load a JSON file once a button on the page is clicked! The request will be using AJAX. I’ve inserted some comments into the code, so it should be easy to understand.

var globalgrid;
function loadgrid()
    type: 'GET',
    dataType: 'json',
    url: 'ajaxdemo.json',
    success: function(griddata)
  	  globalgrid = griddata.lines;

      // remove all data - but the headers!

      if( globalgrid.length === 0)
           $('#errormsg').html('Sorry, no rows returned!');

      for( var i=0; i < globalgrid.length; i++ )
         var line = globalgrid[i];
         // insert after last row! (yes! it *can* be done differently - but it works!)
         $('#gridtable > tbody:last').append(''+line.d1+''+line.d2+''+line.d3+''+line.d4+'');
    error: function(data, errorText)

The reason I save the data from the request in globalgrid is it is easier to debug later on (open the console in Chrome and type “globalgrid;” and you will know what I mean!)

I made a small example ready to run here. You are free to use the code 😉 If you find it usefull, drop me a line 😉

6 Responses to “Load data into table using JQuery and AJAX”

Leave a Reply

You must be logged in to post a comment.