Storing a MySQL string in a JavaScript variable with JSP: A Step-by-Step Guide

I have been trying to store MySQL strings in a JavaScript array variable using JSP for server-side scripting, but I haven't been successful. I could use some assistance.

Attempt-1:

<script>
        var name = [];
  <%
        st=con.prepareStatement("select name from company");
        rs=st.executeQuery();
        while(rs.next()){
            String s = rs.getString(1);
  %>
            name.push(<%=s%>);          
  <%
        } 
  %>
</script>

Attempt-2:

<script>
        var name = [];
  <%
        st=con.prepareStatement("select name from company");
        rs=st.executeQuery();
        while(rs.next()){
  %>
            name.push(<%=rs.getString(1)%>);            
  <%
        } 
  %>
</script>

Attempt-3:

<script>
        var name = [];
  <%
        st=con.prepareStatement("select name from company");
        rs=st.executeQuery();
        while(rs.next()){
  %>
            name.push(<%out.print(rs.getString(1));%>);         
  <%
        } 
  %>
</script>

All three attempts gave the same result and error after processing.

Interpreted Code:

<script>
        var name = [];
        name.push(tcs);
        name.push(wipro);
</script>

Error:

ReferenceError: tcs is not defined

Answer №1

Enclose your string in double quotes and consider encoding it using JavaScript (there are libraries available in Apache that can help with this):

<script>
        var name = [];
  <%
        st=con.prepareStatement("select name from company");
        rs=st.executeQuery();
        while(rs.next()){
            String s = StringEscapeUtils.escapeJavaScript(rs.getString(1));
  %>
            name.push("<%= s %>");          
  <%;
        } 
  %>
</script>

Consider utilizing the Apache library for escaping Java strings according to JavaScript rules: StringEscapeUtils

Ensure that when you use name.push(tcs);, tcs is treated as a string, so make sure to include quotes around it like "tcs" or in this context "<%= s %>".

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

Unable to sort nested JSON data in ngTable

I have successfully built an angularjs application using ngTable, however, I am facing an issue with sorting. The JSON structure is nested but the values are appearing correctly in the table. If anyone has a solution to this problem, please let me know. ...

It never fails to function automatically, no matter which script is being executed

By default, the script will always be executed regardless of its environment. Check out my code snippet: import { Pool } from 'pg'; import config from './../config'; const connectionString = () => { switch (process.env.NODE_EN ...

Encountering an error: Unable to execute function 'releaseConnection' on null object in MySQL with Node.js

Currently, I am utilizing the mysql felix node.js module and making use of its pool connection feature. Within my server-side code (written in node), I have numerous queries structured similarly to the example below: this.courtsAmount = function(date, c ...

Limit how API call costs are set in a function by throttling based on an argument

I am currently implementing express-throttle to restrict the number of API calls per IP address each day. I would like to dynamically set the 'cost' parameter in the 'options' array based on a value from the API request (refer to commen ...

Steps to configure ExpressJS to listen on a custom domain

I'm trying to set up ExpressJS to listen on a specific domain, as I just acquired a new domain. I want Express.JS to be able to listen on this domain without specifying any ports. Can anyone provide guidance on how to accomplish this? If Express doesn ...

What is the best way to swap out an HTML file with another without altering the link?

I'm working on an HTML file, which is basically a webpage. My goal is to create a functionality where clicking a button will dynamically replace the content of the page with another HTML file, complete with its own CSS, JavaScript functions, and other ...

Attempting to extract JavaScript URLs using scraping methods, however, receiving an empty string when utilizing

I need help accessing and extracting data from a URL that is embedded within a specific tag. The tag in question looks like this: <script src="http://includes.mpt-static.com/data/7CE5047496" type="text/javascript" charset="utf-8"></script> S ...

Exploring the capabilities of Zend Framework for fetching data and intricate join operations

Exploring the functionality of the select object has been quite comfortable for me, especially when dealing with less complex queries. I wonder, are there any limitations to using this method instead of manual SQL queries? I would like to incorporate it a ...

Error code 13 occurred while trying to upload information into the SQL database

Currently in the process of loading a file into the database. CREATE TEMPORARY TABLE IF NOT EXISTS tt_emails ( id INT PRIMARY KEY AUTO_INCREMENT, util_account_id VARCHAR(40) NULL, email VARCHAR(344) NOT NULL, optout INT NOT NULL ); L ...

Storing website on S3 from Angular project may cause the initial "loading" screen to not display

In my expansive Angular project, there are numerous HTML, TS, and CSS files. It seems that my website is static since there is no server-side code involved. To deploy my Angular project's directory to my S3 bucket, I am relying on the "s3-website" npm ...

Error message: "Module not found - Electron application"

I've been working on developing an audio enhancer application using electron. However, whenever I click on the enhance button, I encounter this error in the console: (node:7587) UnhandledPromiseRejectionWarning: Error [ERR_MODULE_NOT_FOUND]: Cannot fi ...

Utilizing ng-repeat, filter, and the uib-popup-datepicker to refine and display specific data within a table column

I'm currently facing a common scenario in my Angular application where I need to filter items from an ng-repeat using an HTML5 input of type 'date' or Angular-UI-Bootstrap's 'uib-popup-datepicker'. Despite extensive research, ...

Using MySQL, perform a SELECT query and then proceed to remove records from that query where the column values are equal

Here is my original question: SELECT bid_tag.* FROM bid_tag join (select serial_number, count(*) as cnt from bid_tag where user_id = 0 group by serial_number ) tsum on tsum.serial_number = bid_tag.serial_number and cnt > 1 or ...

Keep a close eye on your Vue app to make sure it's

<template> <v-form :model='agency'> <v-layout row wrap> <v-flex xs12 sm12 lg12 > <v-layout row wrap> <v-flex xs12 md12 class="add-col-padding-right"> <v-radio-group v-mod ...

What is the best way to initiate a call with SWR in NextJs with just the push of a button?

I am attempting to use the useSWR hook when a button is clicked. However, I keep encountering an error when trying to make the API call with useSWR triggered by the button click. The error message reads: Error: Invalid hook call. Hooks can only be called i ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

Tips for utilizing the AngularJS filter to group by two columns in Angular

In my array of objects, each item has three properties: 1. name 2. team 3. age http://jsfiddle.net/HpTDj/46/ I have successfully grouped the items by team, but I am unsure how to group them by both team and age in my current code. I want to display the ...

What could be causing my JavaScript code to not function properly in an HTML document?

Hello, I am a beginner in the world of coding and currently delving into web development. Recently, I was following a tutorial on creating a hamburger menu but I seem to be encountering some issues with the JavaScript code. I have double-checked my Visual ...

Error on Laravel 7: Unable to retrieve resource - the server returned a 400 (Bad Request) status code

Seeking assistance with a technical issue involving Razorpay. I'm encountering difficulty passing a value from the controller to JavaScript in the view. The data-order_id field is not populating, resulting in the error mentioned above, indicating a nu ...

Showing the information obtained from an API request once the user submits the form without the need to reload the page

I am currently working on a form that will take search query requests from users upon submission and then display the results by making an API call. My goal is to show these results without the page having to refresh, using AJAX. The backend connection to ...