1

Datatable was not working. Even console has no errors regarding datatables. Once the page gets loaded, the datatable plugin was not even loading. I tried with cdn links too, still the plugin was not working with my script.

Below is my sample code:

$('#newtable').dataTable( {"pagingType": "full_numbers"} );

<table class="table table-bordered table-hover" id="broker" cellspacing="0">
<thead>
<tr><th class="info">Broker</th>
<th class="info">Address</th>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tbody>
</table>

Scripts and css added:

<script src="-/scripts/jquery.dataTables.min.js"></script>
	
<link href="-/styles/datatables.css" rel="stylesheet"> 

<link href="-/styles/datatables.responsive.css" rel="stylesheet"> 
<script src="-/scripts/datatables.responsive.js"></script>

Here is the exact script I have used to populate the table and map for a page:

  
setTimeout(function() {
  $(document).ready(function() {

// Search button clicked
$('#btnSearch').click(function(e) {
  e.preventDefault();
  $('#searchUserLongitude').val("");
  $('#searchUserLatitude').val("");

  // Do an AREA search
  getBrokerSearchList('AREA');
});

// Hide certain text/functions if geo-location is not available
if (window.navigator.geolocation) {
  window.navigator.geolocation.getCurrentPosition(function(position) {
    $("#findAdvisor").removeClass("hide");
    $("#findAdvisorOr").removeClass("hide");
    $("#findAdvisorText").removeClass("hide");

    $('#searchGpsAvailable').val("Y");
  }, function() {
    //do nothing.
  });
}

  });
}, 1000);

function openInfo(agentCode, lat, lng) {
  var googleMap = this.APP.instances.googleMap;
  googleMap.openInfo(agentCode, lat, lng);
  window.location = '#map';
}

function glSuccess(lat, lon) {
  $('#searchUserLongitude').val(lon);
  $('#searchUserLatitude').val(lat);

  $('#searchTownStreet').val("");
  $('#searchPostCode').val("");
  $('#searchPostCode').trigger('render.customSelect'); // Update the dropdown

  // Do a GPS search
  getBrokerSearchList('GPS');
}

/*
 * Function to call if the browser doesn't support geoLocation or the 
 * user declines to send their position
 */
function glFail() {
  alert('Sorry. Either your browser does not support geoLocation, or you refused the request.');
}

// Get the fund prices
function getBrokerSearchList(typeOfSearchRequested) {
  $("#advisorFinder").addClass("hidden");
  $("#finalSection").addClass("invisible");
  $("#messagePleaseWait").removeClass("hidden");
  $("#messageError").addClass("hidden");
  $("#messageNotFound").addClass("hidden");
  $("#messageErrorService").addClass("hidden");

  var searchTownStreet = $("#searchTownStreet").val();
  var searchPostCode = $("#searchPostCode").val();
  var searchUserLatitude = $("#searchUserLatitude").val();
  var searchUserLongitude = $("#searchUserLongitude").val();
  var searchGpsAvailable = $("#searchGpsAvailable").val();


  // AJAX call to get advisor search data (JSON), and update the page based on it
  $.ajax({
type: 'POST',
url: '/services/findAdvisors?searchTypeOfSearchRequested=' + encodeURIComponent(typeOfSearchRequested) + '&searchTownStreet=' + encodeURIComponent(searchTownStreet) + '&searchPostCode=' + encodeURIComponent(searchPostCode) + '&searchUserLatitude=' + encodeURIComponent(searchUserLatitude) + '&searchUserLongitude=' + encodeURIComponent(searchUserLongitude) + '&searchGpsAvailable=' + encodeURIComponent(searchGpsAvailable),
dataType: "json", //to parse string into JSON object,
success: function(data) {
  if (data) {

    if (data.errors) {
      // We got data back from the service, but there are errors

      // Show/hide the appropriate sections
      $("#advisorFinder").removeClass("hidden");
      $("#messagePleaseWait").addClass("hidden");

      var htmlErrors = "<div class='alert alert-danger custom-alert'>";
      var displayErrors = false;

      // Loop over all of the errors returned and attempt to deal with each one individually
      for (var prop in data.errors) {
        htmlErrors = htmlErrors + "<p>" + data.errors[prop].toString() + "</p>";

        displayErrors = true;
      }

      htmlErrors = htmlErrors + "</div>";

      if (displayErrors) {
        $("#messageErrorService").empty().append(htmlErrors);
        $("#messageErrorService").removeClass("hidden");
      }

      // Tidy up the boxes
      $(window).trigger('resize');
    } else {
      // Update the search results
      var lenAdvisorList = data.findAdvisorResultList.length;
      var htmlAdvisorList = "";
      var protocol = "";

      if (lenAdvisorList > 0) {
        // We have results
        // Build the HTML

        htmlAdvisorList += "<div class='box-simple'>";
        htmlAdvisorList += "<div class='content' style='padding:5px'>";
        htmlAdvisorList += "<div class='table-wrapper' style='margin-top: 15px;'>";

        htmlAdvisorList += "<table cellspacing='0' class='table table-bordered table-hover datatables' id='broker'>";
        htmlAdvisorList += "";

        // Add the table header
        htmlAdvisorList += "<thead>";
        htmlAdvisorList += "<tr>";
        htmlAdvisorList += "<th class='info'>Broker</th>";
        htmlAdvisorList += "<th class='info'>Address</th>";
        htmlAdvisorList += "<th class='info'>Phone</th>";
        htmlAdvisorList += "<th class='info'></th>";
        htmlAdvisorList += "</tr>";
        htmlAdvisorList += "</thead>";

        // Add the table rows
        for (var i = 0; i < lenAdvisorList; i++) {
          if (data.findAdvisorResultList[i].agentNumber) {
            htmlAdvisorList += "<tr data-unqcode=" + data.findAdvisorResultList[i].agentNumber + " data-address=" + data.findAdvisorResultList[i].address + " data-location=" + data.findAdvisorResultList[i].brokerLatitude + "," + data.findAdvisorResultList[i].brokerLongitude + ">";
            htmlAdvisorList += "<td>" + data.findAdvisorResultList[i].agency + "</td>";
            htmlAdvisorList += "<td>" + data.findAdvisorResultList[i].address + "</td>";
            htmlAdvisorList += "<td><a href='tel:" + data.findAdvisorResultList[i].workphone + "'>" + data.findAdvisorResultList[i].workphone + "</a></td>";
            htmlAdvisorList += "<td width='32'>";
            htmlAdvisorList += "<a id='" + data.findAdvisorResultList[i].agentNumber + "' href='#'><img width='32' height='32' src='-/assets/elements/icon_map.png'></a>";
            htmlAdvisorList += "<div class='hidden'>";
            htmlAdvisorList += "<div class='info-window'>";
            htmlAdvisorList += "<p><strong>" + data.findAdvisorResultList[i].agency + "</strong></p>";
            htmlAdvisorList += "<p>Address: <strong>" + data.findAdvisorResultList[i].address + "</strong></p>";
            htmlAdvisorList += "<p>Phone: <strong>" + data.findAdvisorResultList[i].workphone + "</strong></p>";
            htmlAdvisorList += "<p>Email: <strong>" + data.findAdvisorResultList[i].email + "</strong></p>";
            if (data.findAdvisorResultList[i].website != '' && data.findAdvisorResultList[i].website.substring(0, 4) != 'http') {
              protocol = "http://";
            } else {
              protocol = "";
            }
            htmlAdvisorList += "<p><strong>Website:</strong> <a target='_blank' href='" + protocol + data.findAdvisorResultList[i].website + "'>" + data.findAdvisorResultList[i].website + "</a><br/></p>";
            htmlAdvisorList += "</div>";
            htmlAdvisorList += "</div>";
            htmlAdvisorList += "</td>";
            htmlAdvisorList += "</tr>";
          }
        }

        // Clear the existing HTML for the results list
        $('#resultsList').empty();



        // Show the new HTML + other page updates
        if (htmlAdvisorList != "") {
          $("#resultsList").append(htmlAdvisorList);

          $("#advisorFinder").removeClass("hidden");
          $("#finalSection").removeClass("invisible");
          $("#messagePleaseWait").addClass("hidden");
          $("#messageNotFound").addClass("hidden");

          // Initialise the map
          // Will read the data from the table and populate the map
          // Must happen before the datatables update
          APP.instances.googleMap.init();

          // Initialse the datatables

          $('#broker').dataTable({
            "pagingType": "full_numbers"
          });


        }

        // Tidy up the boxes
        $(window).trigger('resize');
      } else {
        // We don't have results

        // Clear the existing HTML for the results list
        $('#resultsList').empty();

        $("#advisorFinder").removeClass("hidden");
        $("#finalSection").removeClass("invisible");
        $("#messagePleaseWait").addClass("hidden");
        $("#messageNotFound").removeClass("hidden");

        // Initialise the map
        APP.instances.googleMap.init();

        // Tidy up the boxes
        $(window).trigger('resize');
      }
    }
  }
},
error: function(jqXHR, textStatus, errorThrown) {
  // We got an error during the AJAX call

  // Clear the existing HTML for the results list
  $('#resultsList').empty();

  $("#advisorFinder").removeClass("hidden");
  $("#finalSection").removeClass("invisible");
  $("#messagePleaseWait").addClass("hidden");
  $("#messageError").removeClass("hidden");
  $("#messageNotFound").addClass("hidden");

  // Initialise the map
  APP.instances.googleMap.init();

  // Tidy up the boxes
  $(window).trigger('resize');
}
  });
}
						

4
  • Why are there dashes in your relative file paths? Commented Apr 12, 2018 at 17:17
  • i just used that for example Commented Apr 14, 2018 at 18:36
  • Did you include jQuery and include it before your other scripts? Commented Apr 14, 2018 at 22:26
  • yes, i reordered the scripts, now my datatable plugin working. but map not gets loading Commented Apr 15, 2018 at 6:48

2 Answers 2

2

The reason is because you're using the wrong table ID. You declared the table with "broker":

<table class="table table-bordered table-hover" id="broker" cellspacing="0">

But then instantiate the DataTable with "newtable":

$('#newtable').dataTable( {"pagingType": "full_numbers"} );

The solution is to change your line to be:

$('#broker').dataTable( {"pagingType": "full_numbers"} );
Sign up to request clarification or add additional context in comments.

1 Comment

Mark gave a good answer after this, hopefully that sorted you out.
0

Any time you're having issues with a library not working as expected, it's usually a good idea to double check the links you're using to request the library. You'll also want to make sure your table markup is correct as well. Lastly, the table id in your html needs to be the same as the selector you use to initialize the table features in your jQuery.

The solution below resolves these issues and works. Hope this helps!

$(document).ready(function() {
  $('#broker').DataTable({
      "pagingType": "full_numbers"
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />

<table id="broker" class="display table table-bordered table-hover" style="width:100%" cellspacing="0">
  <thead>
    <tr>
      <th>Broker</th>
      <th>Address</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>a</td>
      <td>b</td>
    </tr>
    <tr>
      <td>c</td>
      <td>d</td>
    </tr> 
    <tr>
      <td>e</td>
      <td>f</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th>Broker</th>
      <th>Address</th>
    </tr>
  </tfoot>
</table>

9 Comments

i replaced the css and script with above cdn links too, but its still not working.
Use all of the code above - the html, links, and jQuery - and it will work. As you can see, it is working perfectly fine here.
Also, SO isn't a place for general statements like "it isn't working". Please be specific in stating what's not working, any errors you're logging, etc. That helps us debug the issue and determine if it's in fact a coding problem vs a user problem.
sorry, actually my table is populating from an ajax call. the table is populating with out the datatable plugin
yeah, i added above
|

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.