1

I want to load data when button is click but I am having problem it will not load.

$("#search").on('click',function(e){
          $.ajax({
          type:'post',
          dataType:'json',
          url:'tosearch.php',
          data:$('#form1').serialize()',
          success:function(data){
            
              table1.clear().draw();
              table1.rows.add(data).draw();
 
          }
 
      });
 
});
 
 
      $('#form1').DataTable( {
       "scrollCollapse": true,
       "deferRender": true,
       "responsive": true,
       "retrieve": true,
       "columns": [
 
           { "data":"id"},
           { "data": "name"},
           { "data": "age" }
       
 
 
       ]
 
 
   });
 
   var table1= $('#form1').DataTable();

Thank you in advance.

2
  • 1
    Share error in your console and please remove single quote from your ajax call data parameter at last. Commented Sep 20, 2015 at 6:39
  • data:$('#form1').serialize()', has a rogue single quote in it. Commented Sep 20, 2015 at 7:50

1 Answer 1

4

Added code in this jsfiddle. Clicking on Load data button will add json response to datatable. Hope it helps you to move forward.

Check code in action here jsfiddle

$(document).ready(function () { 

    $("#load").on("click", function () {
       loader()
    });

    function loader() { 
        $.ajax({
          type: 'POST',
          dataType: 'json',
          url: '/echo/json/',
          data : { json: JSON.stringify( jsonData ) },
          success: function(data) {
              console.log(data.counters);
              var table = $('#example').DataTable();
              table.clear().draw();
              table.rows.add(data.counters).draw();

          }  
        }); 
    } 

   Table = $('#example').dataTable({
        "data": [],
            "columns": [{
            "title": "id",'data': 'id'
        }, {
            "title": "name",'data': 'name'
        } , {
            "title": "age",'data': 'age'
        } 

        ]
    });

});



var jsonData = {
"success": true,
"counters": [
    {
        "id": "1",
        "name": "Akhil",
        "age": "22"
    },
    {
        "id": "2",
        "name": "Dave",
        "age": "33"
    },
    {
        "id": "3",
        "name": "Chitrank",
        "age": "24"   
    } 

    ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.