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() { $.ajax({ type: 'GET', dataType: 'json', url: 'ajaxdemo.json', success: function(griddata) { globalgrid = griddata.lines; // remove all data - but the headers! $("#gridtable").find("tr:gt(0)").remove(); if( globalgrid.length === 0) { $('#errormsg').html('Sorry, no rows returned!'); return; } 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(''); } }, error: function(data, errorText) { $("#errormsg").html(errorText).show(); } }); } '+line.d1+' '+line.d2+' '+line.d3+' '+line.d4+'
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 😉
April 17th, 2013 at 18:45
You’re missing a demo on http://www.zoon.dk/2012/09/10/load-data-into-table-using-jquery-and-ajax/jquery_load_table_ajax_demo.html – Im looking for some help loading JSON data to table using Ajax.
April 17th, 2013 at 21:07
Weird… don’t know why it’s missing… but you can find the demo here: http://www.zoon.dk/jquery_load_table_ajax_demo.html
May 11th, 2013 at 16:22
I have to ask: How should json file look like for this example?? I’m new with ajax and json and it’ll be much of help for me to understand how it exactly works.
May 11th, 2013 at 23:09
You can find the JSON used in this example here: http://www.zoon.dk/ajaxdemo.json
Most newer, and some old, languages have native support for JSON. What programming language are you using?
May 12th, 2013 at 09:56
Thank you!
August 21st, 2013 at 10:52
Thank you very much!
works great!