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

A guide on triggering a function when the context changes in a React application

Can I automatically trigger a function in a component whenever the context changes? Specifically, I have a variable named isLoggedIn in the Navbar module. Whenever a user logs in, the value of isLoggedIn is updated to true. In my Blog module, how can I m ...

How can I utilize the Json data retrieved through the findById method in my code?

My current project involves creating an API that retrieves data from Patients (id and name), Physicians (id and name), and Appointments (id, phyId, patId, app_date) in order to display the patients scheduled to see a specific physician. To achieve this, I ...

Issue with inline Javascript not functioning correctly when partial is rerendered in Ruby on Rails version 3.1

I am facing an issue in my project where inline JavaScript in a partial, using some instance variables, does not run when the partial is rerendered after a successful ajax call. Could someone please provide guidance on how to solve this problem? For exam ...

Issue: The DLL initialization routine failed for electron, but it works perfectly fine on node.js

Currently, I am facing an issue while attempting to load a custom module in electron that is written in D using the node_dlang package. The module loads successfully with node, but encounters failures within electron. The test run with node, which works w ...

javascript unable to change the text in the textarea

My application takes user input from a textarea element, calls an API to retrieve values, and then compares those values against a list of known "badwords." If a match is found, the word is highlighted in red to indicate it is spelled incorrectly. The pro ...

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

Neglecting specific packages in package-lock.json

Currently facing a perplexing dilemma with no clear solution in sight. In our ongoing project, we rely on npm for package management. Although we haven't been utilizing package-lock.json file lately, the need to reintroduce it has emerged. The issue ...

Ways to add a string to an array as a labeled object in javascript?

Is there a way to manipulate the array in imageCollection to achieve the format of the array in carouselPhotos as shown below? export default class HomeScreen extends Component { state = { imageCollection: [ { name: "P ...

Challenges with Hangman in JavaScript

As a beginner in JavaScript, I recently developed a simple hangman-like game. However, I encountered some challenges that I need help with. One issue is related to my lettersGuessed array. Currently, the array displays every time a key is pressed and repea ...

HTML various button designs - such as a cogwheel

I need a button on my Angular/Electron project that resembles a gear icon. I came across these resources: here and here. However, when I tried to implement them, they didn't work as expected. Currently, the button looks like this: <button class= ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...

Changing the position of an image can vary across different devices when using HTML5 Canvas

I am facing an issue with positioning a bomb image on a background city image in my project. The canvas width and height are set based on specific variables, which is causing the bomb image position to change on larger mobile screens or when zooming in. I ...

javascript The final position achieved through requestAnimationFrame is never precise

let pf = document.querySelectorAll('.pf'); for (let i of pf) { Object.assign(i.style, { left: '400px' }) } function shiftLetters() { let start = performance.now(); let dist = -400; let dur = 500; const logoAnimate = ( ...

Techniques for incorporating a variable into the value field in JavaScript

let y = data[1]; cell1.innerHTML ='<input id="text" type="text" value= "'y'"/>' ; This snippet of code does not render any content when attempting to pass the variable, but if you provide a specific value like "h", it will displa ...

What is the significance of using composability over the deprecated method in Reactjs Material-UI menuItems?

I have taken over a project that was built using an older version of react, and I am currently in the process of updating it. However, I encountered console errors right off the bat. Error : bundle.js:6263 Warning: The "menuItems" property of the "Left ...

Adjust the size of an HTML image for printing using a JavaScript window.print() function

On my website, I have a print option set up where specific elements are hidden using @media. How can I adjust the size of an image within the @media query when my JavaScript print function is triggered? I am able to modify a regular div element easily, but ...

When a StaticFiles instance is mounted, FastAPI will issue a 405 Method Not Allowed response

Running a FastAPI application has been smooth sailing until I encountered an issue. In my current setup, the application script is as follows: import uvicorn from fastapi import FastAPI from starlette.responses import FileResponse app = FastAPI() @app.ge ...

The retrieval of JSON data in a JavaScript function is malfunctioning

I am new to working with Ajax and have reached the point where I am able to retrieve data. However, I am struggling to return the data as I keep getting undefined values. Below is the code snippet: function select_aragement(arragament){ var arrst = ar ...

Navigating through the Express.js routes incorrectly

I currently have 3 different express.js routes set up: app.get('/packages/:name', (req, res) => {...}); app.get('/packages/search/', (req, res) => {...}); app.get('/packages/search/:name', (req, res) => {...}); At t ...

In the ajax call, an empty JSON array object is sent as the data

Utilizing JSON data as a parameter for an ajax call: var startDate = dateFormatForSave($("#start_date").val().trim()); var arrayOfStudentsInfo = []; var table = $("#selected_students"); table.find('tr').each(function(i, el) { var rowId = $( ...