Link to home
Start Free TrialLog in
Avatar of ASPDEV
ASPDEV

asked on

Bind JSon object to the datatable using JQuery

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
Avatar of leakim971
leakim971
Flag of Guadeloupe image

paste the url direclty in the webbrowser, what do you get?
could you paste it?
Avatar of ASPDEV
ASPDEV

ASKER

leakim971, I’m not sure what you are asking for.
do you see this line :         url: url,
@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.
Avatar of ASPDEV

ASKER

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
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.
Avatar of ASPDEV

ASKER

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
Until you can show us what the server is returning we cannot move forward.
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
User generated imageChrome
User generated imageCorrection: For Chrome select the RESPONSE tab to get the RAW JSON - easier to copy from there
Avatar of ASPDEV

ASKER

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"
}
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/
Avatar of ASPDEV

ASKER

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

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

https://datatables.net/manual/ajax
Avatar of ASPDEV

ASKER

I created the data dictionary to load the data as mentioned above, with the way I did can I achieve what I need ??
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ASPDEV

ASKER

Thanks leakim971, It worked as expected.

Julian Hansen, thanks for your support and the help you provided.
you welcome!