Error: my() function is not defined

<input type="button" class="btn" value="Place Order" onclick="myFunction()">


<script type="text/javascript">

  const sessionData = '<% String resp= session.getAttribute("jsonData").toString(); %>';
  const jsonData = JSON.parse(sessionData);
  
function myFunction(){

    alert(JSON.stringify(jsonData));

}




</script>

I am attempting to retrieve a JSP variable and store it in JavaScript, then display it in an alert. However, when I try this, I receive an error saying "function myFunction is not defined".

Answer №1

If you're encountering a JavaScript error, it could be due to a problem in this line of code:

const jso="<%=resp%>"

The variable resp is sourced from an attribute known as jsonData, indicating that it likely contains JSON data. In JSON, properties and string values are enclosed within double quotes. The following example demonstrates the potential error at hand:

const jso="{"key": "value"}"

The opening double quote " should be closed by the final double quote "; however, your JSON seems to close it with the first double quote instead. This results in invalid JavaScript syntax.

To address this issue effectively, consider properly escaping the JSON content. One recommended approach is using Apache Commons Text 1.10.0. By importing the necessary library, you can apply the following solution:

const jso="<%=StringEscapeUtils.escapeJson(resp)%>"

By employing this method, any potentially unsafe characters - including double quotes " within the resp data will undergo proper escaping before being outputted.

Answer №2

This should definitely work. If not, there might be something else causing the issue

Here I'm leaving out the

<% String response= session.getAttribute("jsonData").toString();%>

for clear reasons

window.addEventListener("DOMContentLoaded", () => {
  const data = "<%=response%>";
  document.getElementById("myButton").addEventListener("click", (e) => {
    alert(data);
  });
})
<input type="button" id="myButton" class="btn" value="Proceed to Checkout">

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

Node/Express: The $ symbol is failing to recognize the input for PORT 8080

What steps should I follow to run my PORT on 8080? Is it necessary to install any dependencies? const app = require('express')(); const PORT = 8080; app.listen( PORT, () => console.log('It's now running on http://localhost:$ ...

Selecting a database design pattern for varying database types

After creating a class to manage interactions with my database, I realized that I need separate classes for two different modes: admin and client. class MyDatabase { connect() { /* ... */ } } So, I decided to create two new classes: class MyDatabaseAd ...

What is the best way to confirm that a specific method was called on a JavaScript object using Selenium?

My goal is to use selenium to verify that a specific method (with parameters) was called on a JavaScript Object, similar to expectation mocking with JMockit but for Javascript and selenium. Unfortunately, the object I am dealing with is a heavily obfuscat ...

Send a vanilla JavaScript ajaxForm submission by completing the form

I am currently in the process of integrating JavaScript from an iOS application into a web application. I have control over the code for both apps. My objective is to develop a JavaScript function that can receive input from a barcode scanner, populate a w ...

"CSS background not loading properly on jQuery infinite scroll feature, affecting the loading of

Currently, I am using the most recent version of infinite-scroll developed by paulirish. Everything seems to be working correctly, but there is a peculiar issue that I have encountered. Consider this scenario: You have a forum where infinite scroll is imp ...

Creating a nested JSON response with an Array in a Stored Procedure

I have extracted a dataset from a stored procedure result +------+--------+---------------------+------------+ | Line |Status | Consent | tid | +------+--------+---------------------+------------+ | 1001 | 1 | Yes | ...

A different component experiences an issue where Angular Promise is returning undefined

This is the carComponent.ts file containing the following method: async Download() { try { const settings = { kit: true, tyres: true, serviced: false, }; const [kits, tyres] = await Promise.all([ this.c ...

Task executor now includes a fixed delay

My project utilizes a fixed delay poller in the spring integration (5 min.) that retrieves a group of records, sends them to a splitter for processing, then routes them through a task executor with a pool size of 2. Each record is further processed by a se ...

Content not refreshing when closing and reopening Highslide iframe

I am encountering an issue with Highslide where I am unable to reopen a popup with new content. Even though the contentId remains the same, the content is not being updated when the popup is reopened. Below is the code snippet that showcases the problem: ...

One div on Chrome for Mac is experiencing an issue with applying the background image

I currently have a website hosted on GitHub pages at this link: When viewing the site on Windows Chrome, the bottom div containing the filtering buttons blends seamlessly with the dark grey background set in the wrapper div. However, when viewed on Mac Ch ...

Retrieve the "ready" event following the addition of HTML code

I wanted to share my jsfiddle with you all Check out this JSFiddle link $('#myP').click(function() { GetMap(); }); function GetMap() { var text = '<html lang="en"> <head> <link rel="stylesheet" href="https://cdn.r ...

What methods can be used to identify an array?

Hey there, I'm curious if there's a smart method to determine the current array using the KeyListener? Here's my code snippet: I want to check if the tile I am currently on is BLOCKED. Appreciate any help! ...

What is the best way to incorporate a select dropdown menu into jTable during editing or creation?

When exploring jtable.org and attempting to modify a record on their demo table, one will observe the different field types available such as checkboxes and dropdown menus. However, all the demos and downloaded examples only display textfields for the ed ...

I attempted to establish a connection between my backend and the MongoDB database, however, an error was displayed

Error: Failed to establish a connection to the database! MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 Please check the database connection settings and try again. For more information, refer to the error log. ...

What steps should I take to transform [“link”, “395868”] into [title: “link”, content: “395868”]?

As a newcomer to javascript, I am finding it challenging to articulate my issue due to lack of adequate vocabulary. My current project involves building a chart with d3 and here is the data I require : data=[ ...

Next JS restricts XLSX to return only 100 objects as an array of arrays

I've developed a file upload system that reads Excel files and uploads data to a database (using Mongoose). After implementing the code, I noticed that when I use console.log(sheetData), it returns an array of arrays with objects inside. Each internal ...

Double digit time discrepancies

I am looking to format the TravelTimeHoursDiff and TravelTimeMinutesDiff in double digits. Currently, the time is displayed as 7:0 and I would like it to be displayed as 07:00. if ($scope.DispatchStatus.ArrivalTime != undefined){ var to ...

Using JWPlayer 6 and JWPlayer 7 simultaneously in one project - how is it done?

Trying to incorporate both JWPlayer 6 and JWPlayer 7 into my expressJS, AngularJS project has been a challenge. While they each work independently without issue, bringing them together has proven to be tricky. In my index.html file, I include them separat ...

What is the best way to use a timeout function to swap div layers in AngularJS?

Greetings, esteemed members of the Angular Technorati. I bring forth a perplexing yet seemingly simple issue that requires your expertise. My goal is to dynamically switch out a div layer after approximately 11 seconds and display another div layer. How ca ...

Automated testing with multiple simultaneous users and CAPTCHA verification during login using Selenium WebDriver

My current task involves creating an automated test to determine if a web system is performing at an acceptable speed (steps should not take longer than 1 second), with approximately 100 parallel system users. To accomplish this, I am utilizing Selenium W ...