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.
[sourcecode language=”javascript”]
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, <strong>no</strong> 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(‘<tr><td>’+line.d1+'</td><td>’+line.d2+'</td><td>’+line.d3+'</td><td>’+line.d4+'</td></tr>’);
}
},
error: function(data, errorText)
{
$("#errormsg").html(errorText).show();
}
});
}
[/sourcecode]
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 😉
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.
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
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.
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?
Thank you!
Thank you very much!
works great!