3

I'm trying to load a JSON response from Google Shopping into a table in html formatted using DataTables, the JQuery plugin.

I'm appending the data to the table div but it does not seem to be working.

    <table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Currency</th>
                <th>Price</th>
                <th>Shipping</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
        <tfoot>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Currency</th>
                <th>Price</th>
                <th>Shipping</th>
            </tr>
        </tfoot>
    </table>

    <script>

        var apiKey = "key";
        var country = "US";
        var apiurl = "https://www.googleapis.com/shopping/search/v1/public/products?callback=?";


        $(document).ready(function() { 

          $('#example').dataTable();

            $('.button').click(function (e) {
            $('#example').empty();
        e.preventDefault();

        $.ajax({
        type: "GET",
        url: apiurl,
        dataType: 'jsonp',
            data : 
        {
           key: apiKey, 
               country: country, 
               q: $('[name=myanswer]').val()    
            },
            success: function(data) {
            $.each(data.items, function(i, item){
            if (item.product.images.length > 0) // sanity check
            {
                //global variables
                var link = item.product.images[0]['link'];
                var title = item.product.title;
                var gtin = item.product.gtins[0];

                //price
                var currency = item.product.inventories[0]['currency'];
                var price = item.product.inventories[0]['price'];
                var shipping = item.product.inventories[0]['shipping'];

                var listData = "<li>" + title + gtin + price + currency + shipping + "</li>" + '<img title="' + title + '" src="' + link + '" />';

                var dataTable =
                "<tr>" +
                    "<td>" + '<img title="' + title + '" src="' + link + '" />' + "</td>" +
                    "<td>" + gtin + "</td>" +
                    "<td>" + title + "</td>" +
                    "<td>" + currency + "</td>" +
                    "<td>" + price + "</td>" +
                    "<td>" + shipping + "</td>" +
                    "</tr>";

                        $('#example').append(dataTable).hide().fadeIn('slow');
                        console.log(data)
   }
   });

   }
   });
   });
   });

Update: With Larry's help, I've managed to get the data loading into the table. I know this as the number at the bottom is populated. However, the data is not displaying at all.

<!DOCTYPE html>
<html>
<head>
  <style>
  #images { padding:0; margin:0; overflow: hidden;}
  #images img { width:200px; height:200px; border:none;}
  td {
  padding-top: 2px;
  padding-bottom: 2px;
  padding-right: 20px;
}
  #example img { width:50px; height: 50px; }
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script src="jquery.dataTables.js"></script>
</head>
<body>

<form id="myform">
   <input type="text" name="myanswer" value="test">
   <input type='submit' class="button" name="submitButton" value='submit'>
</form>

<table id="example">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>etc</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
            <td>etc</td>
        </tr>
    </tbody>
</table>

<script>

    var apiKey = "key";
    var country = "US";
    var apiurl = "https://www.googleapis.com/shopping/search/v1/public/products?callback=?";


    $(document).ready(function() { 

    $('#example').dataTable();
            $('.button').click(function (e) {

            $('#example').empty();

                e.preventDefault();

                    $.ajax({
                    type: "GET",
                    url: apiurl,
                    dataType: 'jsonp',
                    data : 
                    {
                        key: apiKey, 
                        country: country, 
                        q: $('[name=myanswer]').val()   

                        },
                    success: function(data) {

                         $.each(data.items, function(i, item){

                            if (item.product.images.length > 0) // sanity check
                            {

                            //global variables
                            var link = item.product.images[0]['link'];
                            var title = item.product.title;
                            var gtin = item.product.gtins[0];

                            //price
                            var currency = item.product.inventories[0]['currency'];
                            var price = item.product.inventories[0]['price'];
                            var shipping = item.product.inventories[0]['shipping'];

                            $('#example').dataTable().fnAddData( [
                            title,
                            gtin,
                            price
                            ]);

                            }
                        });

     }
   });
  });



});


</script>
</body>
</html>
1
  • It is fixed. I forgot to remove the empty method which was forcing the table to show as empty Commented Oct 11, 2011 at 14:53

1 Answer 1

3

Assuming that your AJAX call is working and returning data, the proper way to append a row to a jQuery dataTable is not to attempt to edit the underlying HTML but rather to have dataTable add the row through the dataTable API call fnAddData().

There is an example here.

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

7 Comments

Larry, thanks. I'm pulling the data from Google Shopping API, so where would I put the method?
You should make the following changes: (1) you do not need to format the data as a table row (dataTable will do that for you), so remove all the code and (2) replace the call to $('#example').append(dataTable).hide().fadeIn('slow'); with a call to $('#example').dataTable.fnAddData() with the arguments as shown in the example I linked.
Larry, thanks. I have edited my code but now i'm getting this error: Uncaught TypeError: Cannot read property 'asSorting' of undefined $.fn.dataTablejquery.dataTables.js:7365 c.extend.eachjquery.min.js:30 c.fn.c.eachjquery.min.js:24 $.fn.dataTablejquery.dataTables.js:6923 (anonymous function)google-example.php:90 c.extend.eachjquery.min.js:30 $.ajax.successgoogle-example.php:75 bjquery.min.js:124 c.extend.ajax.A.(anonymous function)jquery.min.js:125 (anonymous function)
Have you correctly constructed the table in the document ready function? You'll need a base table with a header section to receive the data that you're posting, and it will have to be "initialized" as with a previous call to .dataTable().
Larry, i've updated my code, please take a look. Really appreciate your help. Now the data is not displaying at all, but it is being loaded into the table.
|

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.