Is passing a JavaScript variable to a function in Java feasible?

I am currently developing a JSP web page which includes an input text field where users can choose a date. I need to retrieve this selected date value and update it in my database by invoking a Java method that I have created.

The HTML for the input field is as follows:

End Date:<input class="txtEndDate" type="text" id="txtEndDate" name="txtEndDate" readonly/><br><br>

Below is the snippet of my Javascript function:

// function to save data into table
function save() {
    var enddate = $('#txtEndDate').val();
    
    <%
        // function to update the value
        fileFacade.insert_update(id, uniquecode, date, enddate);
    %>
}

Although JavaScript runs on the client side and Java on the back end, I still need to pass the enddate as a function parameter. Is there any way I could achieve this?

EDIT:

updateURL.jsp:

<%@ page import="java.sql.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>

<%@ page import="java.util.Locale" %>
<%@include file="../../../WEB-INF/jspf/mcre.jspf" %>
<%@include file="../../../WEB-INF/jspf/session.jspf"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>


</head>
<body>

<%
    long fileID = Long.parseLong(request.getParameter("id"));
    String uniquecode=request.getParameter("uniquecode");
    String startdt=request.getParameter("startdate");
    String enddate=request.getParameter("enddate");

    int enablestatus= Integer.parseInt(request.getParameter("enable"));

    fileFacade.insert_update(fileID, uniquecode, startdt, enddate, enablestatus);
%>

</body>
</html>

Answer №1

One way to update your data is by making an AJAX call to an API.

See the example code below:

fuction updateData(id, uniquecode) {
  var enddate = $('#txtEndDate').val();
  var radioEnableStatus = $("input[name='radioEnableStatus']:checked").val();
  $.ajax({

    url : 'API URL',
    type : 'POST',
    data : {
        'id' : id,
        'uniquecode': uniquecode,
        'enddate': enddate,
        'radioEnableStatus': radioEnableStatus
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
  });
}

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

Cloud Function experiences a timeout error when attempting to subscribe an FCM token to a topic within the HTTP function

Example Code: Main.ts: import * as admin from "firebase-admin" import fetch, { Headers } from "node-fetch"; interface FooPayload { topic: string, token: string, } exports.foo = functions.https.onCall(async (data, context) => { ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

Add a class to alternate elements when mapping over data in React

Check out the code snippet below: <div className="grid md:grid-cols-2 sm:grid-cols-2 grid-cols-1 gap-16 mt-24 px-4"> {status === "success" && delve(data, "restaurants") && data.r ...

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

Creating a board in Java with 2D arrays and JTable: A comprehensive guide

I've been thinking about creating a JTable. My idea is to use the 2D array's columncount and rowcount to determine the number of rows and columns in the JTable. However, one thing I'm struggling with is how to create fields for each cell in ...

Combining several objects into a one-dimensional array

I am encountering a small issue with correctly passing the data. My form is coming in the format {comment:'this is my comment'} and the id is coming as a number. I need to send this data to the backend. let arr = []; let obj = {}; o ...

What are some ways to effectively utilize Selenium WebDriver and Appium together in a Cucumber test scenario?

I am facing a unique situation where I need to follow a specific process on a website (using Selenium) to create data, which is then transferred to a mobile app. After working on the mobile side (using Appium), I must return to the website to validate the ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

What is the reason for the emergence of this error message: "TypeError: mkdirp is not recognized as a function"?

While running the code, I encountered an error indicating that the file creation process was not working. I am seeking assistance to resolve this issue. The code is designed to fetch data from the Naver Trend API and Naver Advertising API, calculate resul ...

React JS Issue: Real-time Clock not updating in React component

I have a react application designed for attendance tracking. The issue at hand is that the time displayed does not update in real-time. Once the app is initially rendered, the time remains static. (It only updates when the app is reloaded) The code snipp ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

Is it possible to exchange code among several scripted Grafana dashboards?

I have developed a few customized dashboards for Grafana using scripts. Now, I am working on a new one and realizing that I have been duplicating utility functions across scripts. I believe it would be more efficient to follow proper programming practices ...

What is the best way to manage the browser tab close event specifically in Angular, without it affecting a refresh?

I am trying to delete user cookies when the browser tab is closed. Is this achievable? Can I capture the browser tab close event without affecting refreshing? If I attempt to use beforeunload or unload events, the function gets triggered when the user ref ...

In AngularJS, the decimal point is represented by a comma

Several countries use the point as a comma for numbers, and the comma as a decimal separator. This includes Europe (excluding UK and Ireland), South America, Russia, and French West Africa. Find more information on Wikipedia How can we determine if a user ...

Is there a way to randomly select an element from a list and retrieve its text content?

I'm in search of a solution that will allow me to retrieve the text value of a randomly selected element from a dropdown list using Selenium Webdriver in Java. Here is the HTML for the dropdown list: <select name="ctl00$ctl00$ContentPlaceHolder1$ ...

Implement an event listener on the final element of a webpage utilizing querySelector

I need help with a password security check feature that changes field borders to green or red based on certain conditions. Despite successfully implementing it, the JavaScript code only selects the first field (nickname) instead of the last one. I've ...

Fade in images smoothly

Currently, I am in the process of creating a visually appealing image "slider" for a landing page on one of my websites. The slider that I have already created is fully functional and successful, but I am looking to take it up a notch... My goal is to inc ...

WebClient executes JavaScript code

On my aspx page, there are JavaScript functions that handle paging. I am currently using the WebBrowser control to run these JavaScript functions by calling WebBrowser1_DocumentCompleted. WebBrowser1.Document.Window.DomWindow.execscript ("somefunction(); ...

Disabling JMenuBar does not re-enable it when needed

Before showing a FileDialog, I'm disabling the JMenuBar (since the menu items remain active when the FileDialog is open) using getJMenuBar().setEnabled(false), and then re-enabling it with getJMenuBar().setEnabled(true) after the FileDialog closes. Ho ...