Load new data via Ajax

Load new data via Ajax

btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
edited March 2009 in General
Hi Everyone,

I'm using jQuery 1.3.2, Django and DataTables 1.4.

I have a series of drop-downs that filter an object by foreign keys. When a selection is made, an Ajax call is fired, Django renders my JavaScript where I am dynamically creating the table, iterating over objects, etc, and then I eval the returned JavaScript to update the page.

I'm having an awfully hard time getting options like hidden columns and row-level callbacks to fire. Populating the Data Table this way is a snap, and is working properly, but evaling something like:

$('#my_table').dataTable(...{function(nRow, aData, iDisplayIndex){$('td:eq(1)', nRow).html('foo');}...);

Throws all sorts of errors. Am I going about re-populating the Data Table from a dynamic source in the correct manner? If not, what is the preferred way?

TIA,
Brandon
«1

Replies

  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    By re-populating the DataTable in "the correct manner", I mean completely removing the table HTML, resetting it, and re-initializing the DataTable from the evaluated JavaScript returned by my Ajax call.
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Hi Brandon,

    Are you completely altering the table (i.e. changing the columns etc)? If you are just looking to reload the data you can use the fnReloadAjax() API plug-in: http://datatables.net/plug-ins#api_fnReloadAjax

    If you want to completely alter the table, I'd just nuke the old one and replace it with the new...

    Allan
  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    Hi Allen,

    No, columns stay the same, just new data. Sounds like that plugin-is my ticket. What's the implementation on the plug-in?

    Thanks,
    Brandon
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    How do you mean? Just paste the code into your script (before you initialise you table!), then whenever you want to reload the data, call fnReloadAjax() on the table object.

    This example might help: http://datatables.net/examples/example_plugin_api.html

    Allan
  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    Hi Allan,

    Ok, I have placed the fnReloadAjax code above my DataTable init statement, but I'm getting an error: fnReloadAjax is not a function.



    $.fn.dataTableExt.oApi.fnReloadAjax = function(oSettings, sNewSource)
    {
    oSettings.sAjaxSource = sNewSource;
    this.fnClearTable(this);
    this.oApi._fnProcessingDisplay(oSettings, true );
    var that = this;

    $.getJSON(oSettings.sAjaxSource, null, function(json){
    /* Got the data - add it to the table */
    for (var i=0; i
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Remember to use $(document).ready() :-)
    Perhaps something like this will do it:

    [code]
    /* Just after fnReloadAjax... */

    var oTable;
    $(document).ready( function() {
    oTable = $('#activityCodeDataTable').dataTable();

    /* Now call oTable.fnReloadAjax(); whenever you want to reload the table */
    } );
    [/code]
  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    Yes, all of this JavaScript is wrapped by:

    script imports for jQuery 1.3.2 and DataTable

    $(document).ready( function() {
    /* previous code here */
    });

    b
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Got it :-)

    Does the oTable.fnReloadAjax(); call work?
  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    I have a knack for missing the obvious, unfortunately.

    I failed to see where you were assigning the object as the result of binding the table via: $('#my_table').dataTable();

    Now calling the function on the object works, and I'm getting JSON back from the Ajax call, but the table is not updating with the new data, so I need to see what's going on.

    Thank you,
    Brandon
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Very odd. Any chance of posting a link to an example showing the problem?
  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    Unfortunately, I don't have a space to put this on here and won't for a while. I'm just developing everything locally on my Mac and using Django's built-in server.

    Could this be an initialization problem?

    Right now, I'm trying to bring in a set of initial data from an Ajax source, and then re-load it when my drop-downs change values.

    However, even that inital set of JSON isn't populating the table. Example of my JSON:

    {
    "aoColumns" : [
    {"bSearchable" : false, "bVisible" : false},
    null,
    null,
    null
    ],
    "aaData" : [

    [ "4", "Test Code 1", "CC - Information Technology Services", "3/9/2009", "bft228"],

    [ "5", "Django User Group", "CC - Information Technology Services", "3/9/2009", "bft228"],

    [ "6", "Python User Group", "CC - Information Technology Services", "3/9/2009", "bft228"]

    ]
    }

    Here's my initialization string:

    var data_table = $('#activityCodeDataTable').dataTable({
    'bProcessing': true,
    'sAjaxSource' : '/codes/get/' + build_hierarchy_querystring()
    });

    and then in my Ajax call to reload:

    data_table.fnReloadAjax('/codes/get/' + build_hierarchy_querystring());


    The calls are going out fine, and Django is returning the HttpResponse with the JSON, but the rows aren't making their way into the table:




    Title
    CSU
    User
  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    I see where I omitted the date field in the JSON. I added that in, but still no dice.
  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    Got it. Was the id column in the table. I just need to be able to hide that column, and grab it's value to use to create an href around the "title"...
  • btaylordesignbtaylordesign Posts: 10Questions: 0Answers: 0
    This is awesome. Thank you SO much for your help getting this going. DataTables is one of the best jQuery table helpers I've seen to date.

    Kindest regards,
    Brandon
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Awesome - glad you got it going :-). Thanks for the kind words about DataTables - they are very much appreciated!

    Allan
  • rptesterrptester Posts: 1Questions: 0Answers: 0
    This is not working for me in IE 8. fnReloadAjax does not reload the data. Seems like the data is cached
  • sureeshmasksureeshmask Posts: 1Questions: 0Answers: 0
    Can you try this pls?
    oTable = $('#tablename').dataTable();
    oTable.fnClearTable(0);
    oTable.fnDraw();
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Can who try it? This thread is more than a year old...

    Allan
  • rduntonrdunton Posts: 2Questions: 0Answers: 0
    I know this is an old thread but there is a new program in beta at JSONData.org. It's free and will update data in real time. Pretty cool stuff. Hopefully this helps you out.
  • manishdeomanishdeo Posts: 1Questions: 0Answers: 0
    Hi There,

    Could you please share the working code for me? I am also struggling to reload dataTables based on different search.

    It could be helpful if you can share the running code.
    my email ID : deo.manish@gmail.com

    Cheers,
    Manish Deo
  • bhupendrabhupendra Posts: 1Questions: 0Answers: 0
    I am using datatable and i have more data to load init (Approximate 12,00,000 rows including image). when i load my page it got freeze. It is working well when i make limit 10,000 in my query. could you please tell me how can i fix this problem.
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    http://datatables.net/faqs#speed .

    Allan
  • sarevshgupta89sarevshgupta89 Posts: 1Questions: 0Answers: 0
    hi, i am facing a problem while reloading the data into the table..

    i am using a form to select a combination of parameters to load data into table.. when i first time make an ajax call the data loads pretty fine but when i change the options and submit again.. the data is not loading into the table..

    i have used the function fnReloadAjax() but it is saying $.fn.dataTableExt is undefined

    any thoughts?
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Yes - you are loading the plug-in before jQuery, loading jQuery twice or using jQuery as noConflict.

    Allan
  • rajgummarajgumma Posts: 19Questions: 0Answers: 0
    Hi,

    I am currently using datatables for one of my search pages. Now the challenge here is my header columns are not fixed and so are the options in footer. So for each ajax call I am nuking the table and creating a new one

    [code]
    $("table#search").hide();

    $("table#search").html('');
    $("table#search").append(response.data);
    $("table#search").show();

    $("#search").dataTable({
    "bProcessing" : true,
    "bDestroy" : true,
    "bAutoWidth" : true,
    "sScrollY" : "200",
    "sScrollX" : "100%",
    "bScrollCollapse" : true,
    "bSort" : true,
    "sPaginationType" : "full_numbers",
    "iDisplayLength" : 25,
    "bLengthChange" : false
    });
    [/code]

    response.data here gives me a html dom string ........ and I am populating the data into a skeleton

    Everything seems to work fine until a case where there is no data the table and it needs to be completely removed from the jsp. So in that case i did the following

    [code]
    $("table#search").html('');
    $("table#search").hide();
    [/code]

    Sadly this is clearing the data but a dummy datatable with header and footer is remained on the page.
  • timtuckertimtucker Posts: 48Questions: 0Answers: 0
    Why not just have your response.data return the full table?

    If you did that, you could use jQuery's load() to gather the data and then apply the datatable when you're done.

    i.e.: start with the following html
    [code]


    [/code]

    To load the table:
    [code]
    var search = $("#search");

    // Destroy existing data table if present
    search.find(".dataTable").dataTable().fnDestroy();

    // Load the table content
    // (when complete, initialize datatables)
    search.load("/ajaxUrl.html", function() {
    // Look for tables that aren't yet initialized as a data table
    search.find("table").not(".dataTable").dataTable({
    "bProcessing" : true,
    "bDestroy" : true,
    "bAutoWidth" : true,
    "sScrollY" : "200",
    "sScrollX" : "100%",
    "bScrollCollapse" : true,
    "bSort" : true,
    "sPaginationType" : "full_numbers",
    "iDisplayLength" : 25,
    "bLengthChange" : false
    });
    });
    [/code]
  • rajgummarajgumma Posts: 19Questions: 0Answers: 0
    Firstly thanks for such a quick response... This community is full or wonderful people. Special thanks to Alan for making such an awesome plugin

    While running the above code, the dataTables.js threw an error at the following line
    [code] search.find(".dataTable").dataTable().fnDestroy();[/code]

    Error details :

    Message: 'nTableWrapper' is null or not an object
    Line: 5255
    Char: 4

    JS details :

    @summary DataTables
    * @description Paginate, search and sort HTML tables
    * @version 1.9.2
    * @file jquery.dataTables.js

    Appreciate your help and looking for suggestions on this error
  • timtuckertimtucker Posts: 48Questions: 0Answers: 0
    The find(".dataTable") was intended to find a datatable that hadn't already been initialized.

    This might be a safer way of going about the same thing that line was intended for (note: in both cases, completely untested, just what I could think up quickly):
    [code]
    search.find("table").each(function() {
    var isDataTable = $.fn.DataTable.fnIsDataTable( this );
    if (isDataTable)
    {
    $(this).dataTable().fnDestroy();
    }
    });
    [/code]
  • rajgummarajgumma Posts: 19Questions: 0Answers: 0
    Works like magic... Can't thank you more
  • rajgummarajgumma Posts: 19Questions: 0Answers: 0
    Hi Tim,

    There was one more thing i wanted to ask. This pertaining to the pagination feature in datatables

    If you see the example illustrated at the following link,
    http://datatables.net/release-datatables/examples/basic_init/alt_pagination.html

    You will notice that the table contracts while adjusting to the number of rows while moving between 5th and 6th page when showing 10 entries in each page.

    This creates as if the table is jumping on the page, imagine a situation where only one row is present on the last page, then the table is reduced to merely a couple of rows.

    Is there anyway we can handle this ie keep the table width constant in css px and align accordingly with no of rows??
This discussion has been closed.