Munna Babu
Munna Babu

Reputation: 5756

How to load json to datatables on jquery on click function?

I have json data like this and now i need to feed this json data into datatables whenever the search button is clicked based on sending values.

[
{
       "port_code":"BOM",
       "cont_details_id":"9",
       "price":"44.000",
       "cont_price":"500",
       "cont_no":"11",
       "cont_size":"20",
       "cont_type":"GP"
},
{
       "port_code":"BOM",
       "cont_details_id":"10",
       "price":"87.000",
       "cont_price":"500",
       "cont_no":"22",
       "cont_size":"20",
       "cont_type":"GP"        
},
.....
.....
etc.,
]

and this is what i tried in jquery to store json $("#search").click(function() in this function i am calling json file and tried to store in datatables, but its not working. please someone help me from this. Thank you.

$(document).ready(function() 
    {

    var oTable = $('#example').DataTable();

    $("#search").click(function()
    {
        $.post("invoice_ajax.php",
        {
            loc  : $("#location").val(),
            cust : $("#customer_details_id").val()
        },
        function(data)
        {
            $("#text").html(data);
            var s = JSON.parse(data);

                        for(var i = 0; i < s.length; i++) 
                        {   
                            oTable.fnAddData([
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id
                            ]);
                        } // End For
        });
    }); 


    });

Upvotes: 1

Views: 622

Answers (1)

davidkonrad
davidkonrad

Reputation: 85528

You are almost right, except you are using the old 1.9.x fnAddData method on a 1.10.x API. Do this instead :

oTable.row.add([
   s[i].port_code,
   s[i].cont_details_id,
   s[i].price,
   s[i].cont_price,
   s[i].cont_no,
   s[i].cont_size,
   s[i].cont_type
]).draw();

or

var oTable = $('#example').dataTable();
...
oTable.fnAddData([
   s[i].port_code,
   s[i].cont_details_id,
   s[i].price,
   s[i].cont_price,
   s[i].cont_no,
   s[i].cont_size,
   s[i].cont_type
]);

Upvotes: 1

Related Questions