0

I have a JavaScript file that has an Ajax function which calls a JSON file from an online server to extract it's data and interpret it in to a generated table... I want to separate the generate link, generate date, identify the car plate type/country into multiple functions that can be called by the ajax function.

//  table of the server's data from JSON file
$(document).ready(function() {
  $.ajax({
    url: "http://127.0.0.1:3737/anpr?nb=0",
    type: "GET",
    dataType: "json",
    success: function(data) {
      var detection_data = '';
      // generating the table to interpret the json data 
      $.each(data, function(key, value) {
        detection_data += '<div class="table-row">';
        detection_data += '<div class="serial">' + value.id + '</div>';
        // identifie the car plate type/country fron json data
        var plateType = value.plateType
        if (plateType == "1") {
          detection_data += '<div class="country">Tunisie TN</div>';
        } else if (plateType == "2") {
          detection_data += '<div class="country">Tunisie RS</div>';
        } else if (plateType == "3") {
          detection_data += '<div class="country">Tunisie GOV</div>';
        } else if (plateType == "4") {
          detection_data += '<div class="country">Lybie</div>';
        } else if (plateType == "5") {
          detection_data += '<div class="country">Algerie</div>';
        } else {
          detection_data += '<div class="country">Autre</div>';
        }
        detection_data += '<div class="visit">' + value.plateNumber + '</div>';
        // generate date from json data
        detection_data += '<div class="percentage">' + value.date.substr(8, 2) +
          '/' + value.date.substr(5, 2) + '/' + value.date.substr(0, 4) +
          '  ' + value.date.substr(11, 2) + ':' + value.date.substr(14, 2) + ':' + value.date.substr(17, 2) + '</div>';
        // generate link 
        detection_data += '<div>' + '<a class="img-pop-up" href="http://127.0.0.1:3737/anpr/snapshot?year=' + value.date.substr(0, 4) +
          '&month=' + value.date.substr(5, 2) + '&day=' + value.date.substr(8, 2) +
          '&&hour=' + value.date.substr(11, 2) + '&minute=' + value.date.substr(14, 2) + '&second=' + value.date.substr(17, 2) +
          '&plate=' + value.plateNumber.split(" ").join("_") + '&platetype=' + value.plateType + '">link to picture</a>' + '</div>';
        detection_data += '</div>';
      });
      $('#detection_table').append(detection_data);

    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Rojo
  • 2,749
  • 1
  • 13
  • 34
Malek Sfaxi
  • 13
  • 1
  • 2

1 Answers1

0

I tried to make your code more modular and readable. Here's what I could come up with. I am posting only relevant sections of your code to be concise.

NOTE: This is just a recommendation,I have not tested the below code.

      var detection_data = '';
      // generating the table to interpret the json data 
      $.each(data, function(key, value) {
        detection_data += '<div class="table-row">';
        detection_data += getPlateIDHTML(value.id);
        // identifie the car plate type/country fron json data
        detection_data += getPlateTypeCountryHTML(value.plateType);
        // Plate number
        detection_data += getPlateNumberHTML(value.plateNumber);
        // generate date from json data
        detection_data += getDetectionDateHtml(value.date);
        // generate link 
        detection_data += getSnapshotLink(value.date, value.plateNumber, value.plateType);
        detection_data += '</div>';
      });
      $('#detection_table').append(detection_data);

Below are my functions

  String.prototype.format = function () {
    var a = this, b;
    for (b in arguments) {
        a = a.replace(/%[a-z]/, arguments[b]);
    }
    return a; // Make chainable
};

function parseStringAsJSDate(date_as_string) {
  return new Date(date_as_string); 
}


function getPlateIDHTML(id) {
  var plate_id_html = '<div class="serial">%s</div>';
  return plate_id_html.format(id);
}

function getPlateNumberHTML(plateNumber) {
  var plate_number_html = '<div class="visit">%s</div>';
  return plate_number_html.format(plateNumber);

}        

function getPlateTypeCountryHTML(plateType) {
  var plateTypeCountry = {
    "1": "Tunisie TN",
    "2": "Tunisie RS",
    "3": "Tunisie GOV",
    "4": "Lybie",
    "5": "Algerie",
  };
  var plate_type_country_html = '<div class="country">%s</div>';
  if(plateType in plateTypeCountry) {
    return detection_data_html.format(plateTypeCountry[plateType]);
  } else {
    return detection_data_html.format("Autre");
  }
}


function getDetectionDateHtml(captured_date_as_string) {
  var date_of_capture_html = '<div class="percentage">%s/%s/%s %s:%s:%s</div>';
  var captured_date = parseStringAsJSDate(captured_date_as_string);
  return date_of_capture_html.format(captured_date.getDate(), captured_date.getMonth()+1, captured_date.getFullYear(), captured_date.getHours(), captured_date.getMinutes(), captured_date.getSeconds());
}

function getSnapshotLink(captured_date_as_string, plateNumber, plateType) {
  var snapshot_link = "http://127.0.0.1:3737/anpr/snapshot?year=%s&month=%s&year=%s&day=%s&hour=%s&minute=%s&second=%s&plate=%s&platetype=%s";
  var snapshot_link_html = '<div><a class="img-pop-up" href="%s">Link to picture</a></div>';
  var captured_date = parseStringAsJSDate(captured_date_as_string);
  var snapshot_link = snapshot_link.format(captured_date.getDate(), captured_date.getMonth()+1, captured_date.getFullYear(), captured_date.getHours(), captured_date.getMinutes(), captured_date.getSeconds(), plateNumber.split(" ").join("_"), plateType);

  return snapshot_link_html.format(snapshot_link);

}

Below is a brief explanation of each function

  1. String.prototype.format: This is an equivalent of the old-school printf in C. I find variable-substitutions of the sort '<div class="serial">'+ id +'</div>' inter-mingling HTML with JavaScript very difficult to read. And therefore this.

  2. parseStringAsJSDate: I assume that your API is under your control. I recommend you to modify the date format to ISO8601 so that it can be parsed by JavaScript as a Date. Your substr function again affects readability.

  3. getPlateIDHTML & getPlateNumberHTML: Simple functions that just use the format function to embed the passed variables into the HTMLs to show ID and plate number.

  4. getPlateTypeCountryHTML: I used a Python object here to reduce the number of ifs and else ifs.

  5. getDetectionDateHtml & getSnapshotLink: I have tried to parse the date as a JavaScript date and this eliminates the substrs. Moreover, the use of format simplifies these functions further.

Let me know your suggestions on this. Suggestions/Criticism from Stack's gurus are more than welcome :)

UPDATE

Please check my updated format function. I sourced it from this excellent answer. Apologies, the earlier one was just copy-pasted, I should have tried it. Please just the format function to the one that's indicated and let me know

verisimilitude
  • 5,077
  • 3
  • 30
  • 35
  • thank you so much i will give you answere as soon as i try your solution and tell you the result ! – Malek Sfaxi Oct 25 '19 at 15:50
  • the solution worked and th the table is created but i run into a problem where i only see results as s% something like this https://imgur.com/a/yJZAmrv – Malek Sfaxi Oct 26 '19 at 08:55
  • @MalekSfaxi: Check my updated `format` function and use the same. – verisimilitude Oct 26 '19 at 16:14
  • much appreciated i will try your updated solution and tell you about the results ! i know that trying to test a solution is hard in my case because the Json file is provided by a server but i will try everything you asked me and keep you updated – Malek Sfaxi Oct 27 '19 at 17:22
  • 1
    Excellent ! you're edit solved the problem i had, "%s" is now can be recognized and replaced by the appropriate strings again thank you for your help – Malek Sfaxi Oct 28 '19 at 07:48