Improving code quality and consistency in Javascript: Tips for writing better code

Hey, I've been experimenting with some code using ajax and have ended up with a lot of repetitive lines. Is there a way to streamline the code without losing functionality? I keep using the .done method multiple times when I could probably just use it once. Could you help me rewrite this code in a more concise manner? I'm not even sure if this is the best approach to using ajax?

var tbody = $('.tbody');

$('.item').on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
});

$('li a').on('click', function(e) {
  e.preventDefault();
  var link = $(this).attr('href');
  if (link == "books") {
    $.ajax({
      url : "https://mysafeinfo.com/api/data?list=bestnovels1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L",
      dataType : "json"
    })
    .done(function (res) {
      $('.page-header').html(link);
      var text1 = '';
      for(prop in res[0]) {
        text1 += '<th>'+prop+'</th>'
      }
      thead.html(text1);
      var text = '';
      for (var i = 0; i < res.length; i++) {
        text += '<tr>';
      for(prop in res[i]) {
        text += '<td>'+res[i][prop]+'</td>'
      }
        text += '</tr>';
      }
      tbody.html(text);
      
    });
  }else if(link == "novels" || link == "actors") {
    var apiLink = "";
    switch(link) {
      case "novels":
        apiLink = "bestnovels7";
        break;
      case "actors":
        apiLink = "bestactors1";
        break;
    }

    $.ajax({
      url : `https://mysafeinfo.com/api/data?list=${apiLink}&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L`,
      dataType: "json"
    })
    .done(function (res) {
      $('.page-header').html(link);
      var text1 = '';
      for (const prop in res[0]) {
        text1 += '<th>'+prop+'</th>'
      }
      thead.html(text1);
      var text = '';
      for (let i = 0; i < res.length; i++) {
        text += '<tr>';
        for(const prop in res[i]) {
          text += '<td>'+res[i][prop]+'</td>'
        }
        text += '</tr>';
      }
      tbody.html(text);
      
    });

  }

})

Answer №1

It's not as difficult as it seems...

Here is some documentation to help you out:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement#methods
https://developer.mozilla.org/en-US/docs/Web/API/fetch#examples

const urls =
  { books  : 'https://mysafeinfo.com/api/data?list=bestnovels7&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L'
  , novels : 'https://mysafeinfo.com/api/data?list=bestnovels1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L'
  , actors : 'https://mysafeinfo.com/api/data?list=bestactors1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L'
  }
mySelect.oninput =_=>
  {
  myTable.innerHTML = ''         // clear table
 
  fetch( urls[mySelect.value] )  // make server request with chosen URL
  .then(resp=> resp.json() )    // get JSON data from server
  .then(data=>
    {
    let Names = Object.keys(data[0])  // get column names
    data.forEach( row =>             
      {
      let newRow = myTable.insertRow()
      Names.forEach(name => newRow.insertCell().textContent = row[name])
      })
    let newRowHead = myTable.createTHead().insertRow()    
    Names.forEach(name => newRowHead.insertCell().outerHTML = `<th>${name}</th>` )    
                                                 
    })
  }
table {
  font             : 14px Arial, Helvetica, sans-serif;
  white-space      : nowrap;
  border-collapse  : separate;
  border-spacing   : 1px;
  background-color : darkblue;
  margin           : 1em 0 0 0; 
  }
td { padding: .3em .6em; background-color : whitesmoke;     } 
th { padding: .3em .6em; background-color : lightsteelblue; }
<select id="mySelect">
  <option value="" selected disabled >pick one...</option>
  <option value="books" >books</option>
  <option value="novels" >novels</option>
  <option value="actors">actors</option>
</select>

<table id="myTable"></table>

Answer №2

Since the functions in your .done blocks are the same, you can consolidate the code into a single function and call it within each .done block:

.done(res => buildTable(link, res));

Furthermore, you may notice that each Ajax call is almost identical, with only the URL being different. You can create a generic function like this:

function loadTable(link, url) {
  $.ajax({
    url: url,
    dataType: "json"
  })
    .done(function (res) {
      $('.page-header').html(link);
      var text1 = '';
      for (prop in res[0]) {
        text1 += '<th>' + prop + '</th>'
      }
      thead.html(text1);
      var text = '';
      for (var i = 0; i < res.length; i++) {
        text += '<tr>';
        for (prop in res[i]) {
          text += '<td>' + res[i][prop] + '</td>'
        }
        text += '</tr>';
      }
      tbody.html(text);
    });
}

$('li a').on('click', function(e) {
  e.preventDefault();
  const link = $(this).attr('href');
  const links = {
    books: "novels1",
    novels: "novels7",
    actors: "actors1",
  }
  loadTable(link, `https://mysafeinfo.com/api/data?list=best${links[link]}&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L`);
});

You can also simplify the URLs by keeping only the varying parts in the map:

const links = {
    books: "novels1",
    novels: "novels7",
    actors: "actors1",
  }
loadTable(link, `https://mysafeinfo.com/api/data?list=best${links[link]}&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L`);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Flexbox transforms Safari's Horizontal Nav into a Vertical layout

Issue with Horizontal Navigation Bar Turning Vertical in Safari I've been using flexbox to adjust the spacing and size of the li elements as the browser window size changes. Everything works perfectly fine in Chrome and Firefox, but for some reason, i ...

When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking? I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memor ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

Arranging Div Elements in a Specific Layout

I am currently experimenting with http://jsfiddle.net/ngZdg/ My main goal is to create a parallax website, but I am facing some challenges with the initial layout. I am aiming for the following design: ------------------------------------- | ...

Enhancing ASP.NET with jQuery for Efficient Ajax Requests

I have a textBox that uses jQuery to trigger an ajax request: <asp:TextBox ID="postcodeTextBox" runat="server" Text='<%# Bind("POSTAL_ZIP_CODE") %>'> $(document).ready(PageLoad); function PageLoad() { $(container + 'parent ...

Highlighting with pretty JSON formatting

Is there a way to format JSON on a website and emphasize certain text or lines within it? Ideally, I'm looking for an IFRAME service that I can link to a URL where the JSON is downloaded and displayed as HTML. I want to be able to specify a search st ...

Mastering the art of creating data tables

Currently, I am working on a table that involves phone numbers, subscription status, and groups. However, I have encountered an issue where the incoming date is not aligning properly in my table. It seems to be a simple HTML problem, but I am struggling to ...

Ways to align two divs side by side using CSS and HTML

Here is a question that needs solving: I have two elements that need to be displayed in one row at a specific ratio, with the same pattern repeating in subsequent rows. However, the content of the next row is appearing in the unused space of the previous r ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...

The problem I'm facing with the space-between property in my flexbox list

I am working with a list ol that contains items styled as shown below: ol { display: flex; flex-flow: row wrap; justify-content: space-between; width: 400px; } li { width: 120px; height: 120px; } DEMO Currently, I have 3 it ...

Retrieving data from an Ajax request

I am struggling with extracting the HP and PCP Payment fields from the JSON string obtained through a Jquery Ajax request: function DoPaymentSearch() { var start,end; start=Date.now(); var getQuotesSuccess = function(results){ end=Date.now(); alert(JSON.s ...

Unsuccessful attempt at testing RequireJS in a straightforward manner

As a beginner in RequireJS, I am currently experimenting to gain some experience. My goal is to make require load basic Angular first and then manually bring in Angular UI Bootstrap. However, I am encountering an issue where UI Bootstrap complains that ang ...

How can I implement pagination using jQuery?

I'm looking to incorporate jQuery pagination in my CodeIgniter project. After doing some research on the CodeIgniter forum and CodeIgniter AJAX Pagination Example/Guideline, I came across suggestions to check out a solution on TOHIN's blog. Howe ...

Sum text input in a table using jQuery

Whenever the add button is clicked in my code, a new row is generated in the table. I am looking to have each row update the subtotal value automatically when the quantity or price input fields are modified. HTML <table width="100%" border="0" > ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Utilizing Ionic for local data retention

Seeking assistance with connecting my app to local storage in order to save data on the user's device without resetting every time the app is closed. Struggling to link local storage to an array of objects. Any guidance would be highly appreciated. Re ...

Selenium web driver is utilized to perform drag and sort tests on web applications

I've been working on automating the UI of a web page and I need some help. Here is the link to the webpage: Within this webpage, there is an option called Draggable + Sortable. By clicking on this option, an unordered list appears where list items ca ...

Axios failing to include Content-Type in header

I have set up an Odoo instance in the backend and developed a custom module that includes a web controller. Here is the code for the web controller: Web Controller # -*- coding: utf-8 -*- from odoo import http import odoo from odoo.http import Response, ...

Incorporate a font-awesome icon directly within the input field

My div element contains a span element, which in turn includes an i tag. However, the i element extends outside of both the span and div elements. I am attempting to place an eye icon inside an input field. Here is my current code - what adjustments shou ...

JavaScript heap ran out of memory near heap limit during mark-compacts, rendering the allocation ineffective, resulting in a failed Ionic 3 production build

While attempting to build a production version of my Ionic 3 app, I encountered the following error: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory". To troubleshoot this issue, I duplicated the en ...