bsen
bsen

Reputation: 15

Jquery datatable plugin not loading

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');
}
  });
}
						

Upvotes: 1

Views: 1842

Answers (2)

Rich
Rich

Reputation: 3336

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>

Upvotes: 0

colin0117
colin0117

Reputation: 1542

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"} );

Upvotes: 2

Related Questions