What is the correct way to insert a variable into a URL using a JavaScript template literal in Oracle APEX?

While attempting to create a URL in Oracle APEX JavaScript using a template literal, I encountered an issue where the variable was not interpolated correctly. Rather than obtaining the expected URL, the variable name appeared distorted.

Here is what I am currently doing:

const test = `url("f?p=&APP_ID.:1:&APP_SESSION.:APPLICATION_PROCESS=GETIMAGE:NO::IMAGE_ID:1745")`;
console.log(test);

This results in the following functional URL:

url("/ords/r/pj/employee-self-service-portal/home?image_id=1745&request=APPLICATION_PROCESS%3DGETIMAGE&session=890152562441&cs=12Y_buvBPIPUg6fQgAiURQM6QvOyCwIKjlcewXmOTiJMfdOkwT0QubRWuzmRHaSAuwXBtH4iDjQl1YMNWm72OXw")

Now, my objective is to utilize a variable instead of hardcoding 1745.

For instance:

const imageId = 1745;
const test = `url("f?p=&APP_ID.:1:&APP_SESSION.:APPLICATION_PROCESS=GETIMAGE:NO::IMAGE_ID:${1745}")`;
console.log(test);

This outcome displays:

url("/ords/r/pj/employee-self-service-portal/home?image_id=%24%7BimageId%7D&request=APPLICATION_PROCESS%3DGETIMAGE&session=890152562441&cs=1dtlavkb6EP2nlZk9_KxMOcV6GSGzUTtKOAYodnsYe-DshAwwwSIr-pVAqpEb82XGSIHELUFeWMdJxKc5LrrAJQ")

The variable indeed remains unset

The AJAX process follows as such (an Application Process):

DECLARE
  l_lob     BFILE;
  v_pic     blob;
  l_length  NUMBER;
BEGIN
--
select picture into v_pic from pjpayroll.hremp WHERE pkcode = :IMAGE_ID ; --461;

  l_length := DBMS_LOB.getlength(v_pic);
  htp.flush;
  htp.init;
  htp.p('Content-length: ' || l_length);
  htp.p('Content-Disposition: inline; filename="&REQUEST."');
  owa_util.http_header_close;
  wpg_docload.download_file(v_pic);
EXCEPTION WHEN OTHERS THEN NULL;
END;

I am aiming to develop an Organization Chart utilizing the third-party d3.OrgChart Library

var chart;
function fetchDataAndShowAlert() {
    d3.csv(
        '#APP_FILES#TEST.csv'
      ).then((dataFlattened) => {
        chart = new d3.OrgChart()
          .container('.t-Body-mainContent')
          .data(dataFlattened)
          .nodeHeight((d) => 85)
          .nodeWidth((d) => {
            return 220;
          })
          .childrenMargin((d) => 50)
          .compactMarginBetween((d) => 25)
          .compactMarginPair((d) => 50)
          .neightbourMargin((a, b) => 25)
          .siblingsMargin((d) => 25)
          .buttonContent(({ node, state }) => {
            return `<div style="px;color:#716E7B;border-radius:5px;padding:4px;font-size:10px;margin:auto auto;background-color:white;border: 1px solid #E4E2E9"> <span style="font-size:9px">${
              node.children
                ? `<i class="fas fa-angle-up"></i>`
                : `<i class="fas fa-angle-down"></i>`
            }</span> ${node.data._directSubordinates}  </div>`;
          })
          .linkUpdate(function (d, i, arr) {
            d3.select(this)
              .attr('stroke', (d) =>
                d.data._upToTheRootHighlighted ? '#152785' : '#E4E2E9'
              )
              .attr('stroke-width', (d) =>
                d.data._upToTheRootHighlighted ? 5 : 1
              );

            if (d.data._upToTheRootHighlighted) {
              d3.select(this).raise();
            }
          })
          .nodeContent(function (d, i, arr, state) {
            const color = '#FFFFFF';
            return `
            <div style="font-family: 'Inter', sans-serif;background-color:${color}; position:absolute;margin-top:-1px; margin-left:-1px;width:${d.width}px;height:${d.height}px;border-radius:10px;border: 1px solid #E4E2E9">
               <div style="background-color:${color};position:absolute;margin-top:-25px;margin-left:${15}px;border-radius:100px;width:50px;height:50px;" ></div>
               <img src="f?p=&APP_ID.:1:&APP_SESSION.:APPLICATION_PROCESS=GETIMAGE:NO::IMAGE_ID:1745" style="position:absolute;margin-top:-20px;margin-left:${20}px;border-radius:100px;width:40px;height:40px;" />
              <div style="font-size:15px;color:#08011E;margin-left:20px;margin-top:32px"> ${
                d.data.name
              } </div>
              <div style="color:#716E7B;margin-left:20px;margin-top:3px;font-size:10px;"> ${
                d.data.positionName
              } </div>
           </div>`;
          })
          .render();
      })
}

Although it is functioning, all images are associated with the ID 1745. My intention is to make it dynamic by passing the value from d.data.id instead of 1745.

Looking forward to responses.

Answer №1

There are two potential solutions for this issue, both of which involve making a server-side call. If the page requires a checksum (which is highly recommended), generating the URL using JavaScript is not feasible. Instead, the URL must be created in the database.

  1. If the task is to be executed upon loading the page, you can utilize a before rendering process or computation that calls the APEX_PAGE.GET_URL PL/SQL API. This method will ensure that the checksum is calculated accurately.

-or -

  1. Alternatively, you can use JavaScript to generate the URL by implementing an Ajax callback process defined within the APEX page (which can also be done at the application level).

Nevertheless, it is essential to reassess the business requirements. Just because JavaScript seems like a solution does not necessarily mean it is the best option; perhaps utilizing a data attribute with the variable "imageId" in the chart and creating the URL through a dynamic action on click could be more effective.

One alternative is to create a demo on apex.oracle.com and share the login credentials here for further evaluation.

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

Encountering an error in AngularJS $http calls while trying to loop: TypeError - object is not functioning

Currently, I am in the process of automating the population of my app's database with Dummy Data to eliminate the manual task of adding users, friends, and more. To achieve this, I have implemented nested AngularJS $http requests that interact with my ...

Exploring touch events and input focusing on mobile devices using JavaScript

Recently, I integrated a JS touch mapping function into one of my pages sourced from Stack Overflow. This was necessary to enable my jQuery draggables to work on iOS Safari, as drag and drop functionality was not functioning without this mapping. Here is ...

extract information from a document and store it in an array

As I delve into the realm of programming, I find myself grappling with the best approach to extract data from a file and store it in an array. My ultimate aim is to establish a dictionary for a game that can verify words provided by players. Despite my no ...

Is it considered acceptable to invoke an asynchronous function that retrieves initial data within the constructor of a JavaScript class?

Currently, I am working on a sample application using Mobx and Mobx React Lite to gain a better understanding of this state management tool. When a user accesses the page, the app should load questions. I have some doubts regarding whether it is advisable ...

How to successfully send data props from child components to parent in Vue3

I am currently working on a personal project to add to my portfolio. The project involves creating a registration site where users can input their personal data, shipping information, and then review everything before submission. To streamline the process ...

Attempting to adjust numerical values to display with precise two decimal places using jQuery

Possible Redundancy: JavaScript: how to format a number with only two decimal places I'm getting confused while using variables and now I can't seem to get the calculation working correctly. Any ideas? $("#discount").change(function(){ ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

Optimal approach for incorporating AJAX/jQuery functionality to both append to a form and refresh a list simultaneously on a single webpage

Currently, I am developing a page that consists of a form to input data into a table, as well as a list displaying items from that table. My goal is to ensure that the newest items appear at the top of the list after the form submission. At the moment, t ...

Ways to display a block within the visible window by simply clicking on another block

I'm in need of assistance with this issue. Please take a look at the fiddle link below to understand the specific requirement. $(document).ready(function(){ $('a.n-stand-b, a.n-stand-a, a.e-stand-b, a.e-stand-a, a.w-stand-b, a.w-stand-a, a.s-s ...

React 18 introduces a new feature, ReactDOMClient.createRoot(), which allows for hot module replacement with Webpack. This allows developers to update components in real time without

After upgrading React to version 18, I encountered a console error with my Webpack dev server when the hot module replacement triggers and injects new JavaScript code: Warning: You are calling ReactDOMClient.createRoot() on a container that has already be ...

Button Vote in Bootstrap is unresponsive

I have a voting system implemented on my website using normal CSS buttons, and it works perfectly fine. However, when trying to integrate it with Bootstrap buttons, it seems to not function properly. I am looking to switch to using Bootstrap buttons for t ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

Sending a variable to the resize() function in jQuery

Currently, I am working with two specific divs in my project: "#sidebar-wrapper" and ".j1". The height of ".j1" is dynamic as it changes based on its content. My objective is to set this height value to the "#sidebar-wrapper" element. I have attempted to ...

Struggling with synchronicity in javascript(node.js) and seeking assistance

I am faced with a challenge in my express.js app where I need to execute a script on the server, followed by running a couple of functions to derive some values. The process should be sequential, but I am running into issues as JavaScript seems to move on ...

What is the best method for installing Raphael.js using bower?

Currently, I am attempting to incorporate Raphael.js into my project in a highly modular manner. Since Raphael has a registered bower component, utilizing that option seemed like the most logical choice. Following some instructions from the Snap.svg readm ...

Bootstrap Tags Input is unable to function properly with data stored locally

I am currently working on developing a Project Manager tool that allows for the addition of multiple individuals to a single project. To accomplish this, I decided to incorporate the use of Bootstrap Tags Input by following the examples provided for Typeah ...

Running a JavaScript test using the Mocha framework with an 'import' statement for a JS file

I am familiar with the module.export and require method: Requiring external js file for mocha testing While it is useful when dealing with modules, I find it inconvenient as I now need to test code in a specific file. For example, I have code in a file: ...

JavaScript getting overshadowed by other JavaScript libraries

My current CMS, Liferay, heavily relies on jQuery for various functions. Recently, I introduced a new feature to our website using fancybox. However, I realized that this new addition was causing issues with other jQuery functionalities on the page. Remov ...

Pulling images into an array using AJAX

I am trying to create an array of all images in a specified image folder. After searching for similar questions on stackoverflow, I am now feeling a bit stuck. var folder = "images/"; $.ajax({ url: folder, success:function(data){ functi ...

Converting an MVC form into JSON using Jquery

I am encountering an issue with serializing my MVC form to JSON using JQuery and then deserializing some values, like the input field value, on the backend in C#. I have tried to serialize it in JSON without success. Can someone please assist me with this ...