Bind JSon object to the datatable using JQuery

ASPDEV
ASPDEV used Ask the Experts™
on
Hello Experts,

I'm new to MVC and JQuery web development. I'm trying to bind the data to my datatable using JSon object. Below is the sample code:

View
<div id="mdlMsg" class="modal fade" tabindex="-1" role="dialog">
            <div class="table-responsive m-t-40">
                <table id="dtData" class="display nowrap table  dataTable" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th>Col1</th>
                            <th>Col2</th>
                        </tr>
                    </thead>
                    <tbody id="tblbody"></tbody>
                </table>
            </div>
        </div>

Open in new window


Controller
public async Task<ActionResult> Test()
{
 string resp = "";
  var msg = new Dictionary<int, string>();
msg .Add(1, 'Row 1');               
msg .Add(2, 'Row 2');       
      resp= Newtonsoft.Json.JsonConvert.SerializeObject(msg, Newtonsoft.Json.Formatting.Indented);
return resp;
}

Open in new window


Javascript
$.ajax({
        type: 'post',
        url: url,
        processData: false,
        contentType: false,
        data: files,
        success: function (resp) {
 $('#mdlMsg').modal({ show: true })
                var jsonTst = $.parseJSON(resp);
                $('#dtData').dataTable({
                    "bAutoWidth": false,
                    "aaData": jsonTst.data,   //this is your JSON object, which is what is showing in your post above with console.log(data)
                    "aoColumns": [{
                        "jsonTst": "Col1"
                    }, {
                            "jsonTst": "Col2"
                    }]
                });
});

Open in new window


The modal popup shows with no data and also I want to fix my Modal popup to be middle of the page.

Thanks,
ASPDEV
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
leakim971Multitechnician
Top Expert 2014

Commented:
paste the url direclty in the webbrowser, what do you get?
could you paste it?

Author

Commented:
leakim971, I’m not sure what you are asking for.
leakim971Multitechnician
Top Expert 2014

Commented:
do you see this line :         url: url,
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
@ASPDEV,
Leakim is asking you to test the AJAX URL.

If you take whatever the value is for url in your code (line 3) paste that into the Address Bar of your browser - what do you get back?

AJAX is no different from a Browser - in the case of a GET request you can paste the URL into the browser and see what is returned.

What is being asked for here is a test to see if the URL is working and returning data. No point in looking at the JavaScript if the URL does not work.

Author

Commented:
Hello leakim & Julian Hansen,

I cannot copy the url(on quick watch it says not available), but I can click on it(like a play button) and it opened the Modal popup. Attached is the screenshot and I didn't get any data but the modal popup shows up with the column names and header. Please suggest what I'm doing wrong.

This is the serialized data after JSON parsed in JavaScript and assigned to datatable.

"{
  "1": "Row 1",
  "2": "Row 2"
}"

Open in new window

test.JPG
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
I cannot copy the url
That URL is defined somewhere on the page.
Even if you copy out of the console window.
F12
Go to console
Make sure that XHR logging is on
Initiate the AJAX call
You should see the URL show int the console.
If you cannot then switch to the Network tab of the console.
Repeat the process.
From either console or network tabs you can right click the Link and chose copy link.

My preference is Firefox for this but you should be able to do it in Chrome.

Once you have copied the link - open a new tab, paste and execute.

Author

Commented:
Julian Hansen,

Sorry.. I'm not able to achieve the steps to follow. But tried the way how in other places they did and did hard-code the data to see what I get
$.ajax({
        type: 'post',
        url: url,
        processData: false,
        contentType: false,
        data: files,
        success: function (resp) {
 $('#mdlMsg').modal({ show: true })
             var data = "1234755";
 $('#dtData').DataTable().destroy();
                 var html = '';
                for (var i = 0; i < data.length; i++) {
                    var obj = data[i];

                    html += '<tr>'
                    html += '<td>' + obj + '</td>';
                    html += '<td>' + obj + '</td>';               

                    
                    html += '</tr>';
                }
                $("#dtBody").append(html);
});

Open in new window


Now I see the data like this (attached), I want something like that but my data I have is in different format. I need to format that so I can show. How can I have data parsed it in that format to assign it to the $("#dtBody") added this( <tbody id="dtBody"></tbody>) under datatable. I need to parse the data with Comma separated(for rows) and then colon separated(for  columns) and assign to the <TR>

Sample data(after serialized)
"{
  "1": "Row 1",
  "2": "Row 2"
}"


Thanks,
ASPDEV
test.JPG
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Until you can show us what the server is returning we cannot move forward.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Please try this
1. Restore your AJAX to the normal operation fetching from the server
2. Open your site in Chrome or Firefox
3. Press F12 to open the console
4. Initiate the AJAX call
5. Look at the response in the console

See the attached images
Firefox
FirefoxChrome
ChromeCorrection: For Chrome select the RESPONSE tab to get the RAW JSON - easier to copy from there

Author

Commented:
Hello Julian Hansen,

Thanks for the steps provided and it helped me. I was using chrome and below is what I got

Under Response Tab:
{
  "1": "Row 1",
  "2": "Row 2"
}
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Just to clarify - are you using the standard DataTable plugin or a different one?

Your instantiation of the data table uses dataTable rather than DataTable and also refers to aadata - which does not tie in with the standard dataTables syntax https://datatables.net/

Author

Commented:
I'm using the DataTable plug-in. Below is my html code

<div id="mdlMsg" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Test</h4>
                    </div>
                    <div class="modal-body">
                        <div class="table-responsive m-t-40">
                            <table id="dtData" class="display nowrap table  dataTable" cellspacing="0" width="100%">
                                <thead>
                                    <tr>
                                        <th>Col1</th>
                                        <th>Col2</th>
                                    </tr>
                                </thead>
                                <tbody id="dtBody"></tbody>
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
So then why not just use the DataTables ajax function to load your data

https://datatables.net/manual/ajax

Author

Commented:
I created the data dictionary to load the data as mentioned above, with the way I did can I achieve what I need ??
Multitechnician
Top Expert 2014
Commented:
try this code :
    <script>
        $.ajax({
            type: 'post',
            url: "data.json",
            processData: false,
            contentType: false,
            data: files,
            success: function (resp) {
                $('#mdlMsg').modal({show: true})
                $('#dtData').DataTable().destroy();
                var html = '';
                for (var k in resp) {
                    html += '<tr>'
                    html += '<td>' + k + '</td>';
                    html += '<td>' + resp[k] + '</td>';
                    html += '</tr>';
                }
                $("#tblbody").append(html);
                $('#dtData').DataTable();
            }
        });
    </script>

Open in new window

Author

Commented:
Thanks leakim971, It worked as expected.

Julian Hansen, thanks for your support and the help you provided.
leakim971Multitechnician
Top Expert 2014

Commented:
you welcome!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial