0

I have an ajax function whose response is in the form of html and has the following contents.

<tr><td>data1</td>td>data1</td>td>data3</td></tr>

Is it possible to add the response to dataTable row like this

$.ajax({
                type:"POST",
                url:myurl,
                data:myformdata,
                cache: false,
                contentType: false,
                processData: false,
                success:function(hasil){  
                    if($.parseHTML(hasil))
                    { 
                        if($(hasil).filter('table').length)
                        {
                          $('#lstNews').DataTable().row.
add($(hasil).filter('table').html()).draw();
                        }

                    }
         });

In the google I have found that I need to make the response to the following format for adding it to dataTable

$('#lstNews').DataTable().row.add(
   [[ "data1", "data2","data3" ]
     ]
).draw();

Please help me

1 Answer 1

1

You can use jQuery's parseHTML function on the response, and use maping to fetch the html/data from each of the td's into an array.

EDIT: Removed arrow function for non ES6 support.

var str = '<tr><td>data1</td><td>data1</td><td>data3</td></tr>';

var html = $.parseHTML(str);

console.log($('td', html).map(function(_, el) {
  return $(el).html()
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

2 Comments

When I am copying the code,its giving me some error in the => section .Also if my response is having multiple rows ,can I use the same code for parsing???
@Techy Feel free to do a little research on your own to loop through the TR's, and add them each to the DataTable.

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.