What is the best way to save request URLs in JavaScript while following the DRY principle?

Is there a standard practice in JavaScript for storing the URLs of endpoints used in AJAX applications?

Would you, for instance, consider creating a "Service" class to encapsulate the URLs?

Answer №1

If you want to keep track of URL values and identifiers, one approach is to create a collection using ValuePairs:

function Pair(id, value) {   
    this.id = id;
    this.value = value;
}

function createCollection(className) {    
    var obj = new Array();
    eval("var t = new " + className + "()");
    for (_item in t) {
        eval("obj." + _item + " = t." + _item);
    }
    return obj;
}

function ValuePairsCollection() {
    this.container = "";
    this.add = function(obj) {
        this.push(obj);
    }
}

After creating the collection, you can easily iterate through it or search for specific IDs.

Answer №2

In my experience working with Rails, I've implemented a solution similar to the following:

NAMESPACE.categories.baseUri = '/categories';
NAMESPACE.categories.getUri = function(options)
{
  options = options || {};
  var uri = [NAMESPACE.categories.baseUri];

  if(options.id)
  {
    uri.push(options.id); 
  }
  if(options.action)
  {
    uri.push(options.action);
  }
  if(options.format)
  {
    uri.push('?format=' + options.format);
  }

  return uri.join('/');
}

Answer №3

Have you come across a previously answered question like this one? If so, does the provided solution also work for your code?

Answer №4

Deciding where to keep your global variables is a personal decision. To prevent clashes in the global namespace, it's recommended to encapsulate them within an object. Therefore, creating a global object like Service would be beneficial for housing URLs and other frequently used strings.

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

Changing the rotation of an object in THREE.js to match Canvas rotation

Hello amazing minds of stackoverflow. I am in the process of converting three js mesh positions to html5 canvas positions. While I have successfully converted vector3 position to canvas position, I am facing difficulties with converting mesh rotation to ca ...

Using Selectpicker with Jquery .on('change') results in the change event being triggered twice in a row

While utilizing bootstrap-select selectpicker for <select> lists, I am encountering an issue where the on change event is being triggered twice. Here is an example of my select list: <select class="form-control selectpicker label-picker" ...

Trigger a page refresh when you revisit it

Currently, I am utilizing Nuxt in SPA mode and my page structure is set up like this: pages ... - users/ - - index - - new - - update/ - - - _id ... I have a page dedicated to displaying a list of users along with a 'subpage' for adding new u ...

What is the best way to capture user input using an onClick event in JavaScript and then display it on the screen?

I'm in the process of upgrading a table, and while most of it is working fine, there is one function that's giving me trouble. I want this function to return an input with an inline onClick event. The actual return value is displaying correctly, ...

How to convert table headings in Bootstrap-Vue.js

For a few nights now, I've been struggling to translate the table header in my vue.js component. It seems like I'm missing something as I'm new to Vue.js and can't seem to figure out what's wrong. Translating within the HTML works ...

Switching to a different view in a React Native application

I am encountering difficulties while navigating between pages in my React Native application. Whenever I try to use the button, an error message pops up saying: TypeError: undefined is not an object (evaluating '_this.props.navigation'). My app c ...

Does the functionality of JSON.parse include recursion?

After receiving a JSON string in response, I parse it as follows: ring = JSON.parse(response); However, although ring becomes an object, the property ring.stones is only a string when it should also be an object. To address this issue, if I execute: ri ...

Error message occurs when creating a pie chart with invalid values for the <path> element in Plottable/D3.js

For those who need the code snippets, you can find them for download here: index.html <!doctype html> <html> <head> <meta charset="UTF-8"> <!-- CSS placement for legend and fold change --> </head> <body ...

set the checkbox's value

<input type="checkbox" name="chkbox" onclick="Utility('<%# Eval("id") %>');" checked='<%# Eval("Contacted") %> ' /> onclick triggers AJAX to update the corresponding record in the database based on whether the check ...

Looking for a jquery plugin that allows you to easily toggle between showing and hiding elements

I'm in need of some guidance on finding a slide window plugin in jQuery. My goal is to create a feature similar to Yahoo Mail, where users can hide the advertisement pane shown on the right side by clicking a button. I would greatly appreciate any as ...

I am struggling to make php redirect work using onclick() function

My PHP button is not redirecting properly. Assuming the page destination is correct, is there anything else that could be causing this issue? echo "<button id=\"create\" onclick=\"location.href('/team/teams.php?op=create');&bso ...

Ways to address the CORS problem in an ajax function without relying on json

When I run my ajax function: function fn_nextitem(sliderNo){ $.get("/index.php?op=ajax", {slide_no:sliderNo},function(resp) { if (resp) { $('#Div').append(resp); } else { } } This is how my ph ...

Retrieve a unified data array from the provided data source

Below is a snapshot of my data const data = [{"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw ...

Utilize angularjs daterangepicker to refine and sift through data

I am currently utilizing the ng-bs-daterangepicker plugin by ng-bs-daterangepicker and encountering difficulty in filtering when selecting a start date and end date. Below is a snippet of my code: <input type="daterange" ng-model="dates" ranges="range ...

Dealing with numerous Ajax calls within a single Ajax request

I am utilizing the $http method in angularjs to retrieve multiple "parent" elements. Within the success method of these Ajax calls, I need to loop through the parent elements and make another Ajax call for each parent element to fetch its corresponding chi ...

The expected result is not obtained when making an Ajax request to a PHP variable

I recently encountered an issue with my AJAX GET request. The response I received was unexpected as the PHP variable appeared to be empty. Here is the snippet of jQuery code that I used: jQuery(document).ready(function($) { $.ajax({ url: '/wp ...

The npm command encountered a permission issue when trying to install node-sass

Whenever I run the npm command on my Ubuntu system, I encounter a "permission denied" issue. sudo npm install node-sass EACCES: permission denied, access '/node_modules/node-sass' I have attempted to run the command as a root user or with sudo ...

What causes the ongoing conflict between prototype and jquery?

I have researched how to effectively load both prototype and jQuery together, but the solutions I found did not resolve my issue. My current setup involves loading jQuery first, followed by this specific file: http:/music.glumbo.com/izzyFeedback.js, and t ...

express backend returns empty request body when fetch is used

I am currently working on a nodejs application that involves two scripts, server.js and script.js. Below are snippets of the relevant code in both files: script.js const topic = document.getElementById("topic").value; console.log(" ...

Creating a seamless navigation experience with Next.js: Implementing per-page layouts for efficient 2-link navigation on a single screen

In my next.js project, I have a URL like "http://localhost:3000/forum". If a user goes to "http://localhost:3000/forum/{postId}", I want to redirect them back to "http://localhost:3000/forum" My folder structure is in the 'App' directory and I h ...