Assigning session attributes with javascript

Incorporating the jqueryui autocomplete combobox on my jsp page, I am looking to assign the selected value of the combo-box to the HttpSession.

My attempted solution was:

this._on(this.input, {
    autocompleteselect: function (event, ui) {
        // alert(ui.item.value);
        var value = ui.item.value;
        <% session.setAttribute("comboboxvalue", value); %>  

        ui.item.option.selected = true;
        this._trigger("select", event, {
            item: ui.item.option
        });
}

The issue with this approach is that the code does not recognize the value parameter.

How can I address this and establish a session attribute using javascript?

Answer №1

There is a common misunderstanding that jsp and javascript exist in the same file. However, the JSP part compiles on the server side and then comes to the client.

The code enclosed within <% %> executes on the server side.

You cannot achieve this with Javascript.

In order to accomplish this, you need to make a server request (using forms, Ajax, URLs, etc.).

Answer №2

JavaScript is primarily used on the client side of web development. It is not capable of setting session variables directly from within JavaScript code.

To achieve this functionality, you can utilize Ajax. By making an asynchronous request to the server using Ajax, you can then manipulate and update the session data from the servlet on the server side.

Answer №3

I successfully completed my task by following these steps:

To start, I developed a new servlet and initiated an AJAX call as shown below. Subsequently, I stored the value of comboboxvalue in the session from the servlet.

this._on( this.input, {
    autocompleteselect: function( event, ui ) {
        $.ajax({
        type: 'POST',
        url: 'AjaxServlet',
        dataType : 'json',
        data: { comboboxvalue : ui.item.value  }
        });
        ui.item.option.selected = true;
        this._trigger( "select", event, {
            item: ui.item.option
        });
    },

    autocompletechange: "_removeIfInvalid"
});

Answer №4

It is not possible to directly set session values using JavaScript.

In this situation, a solution could be to use an AJAX call triggered by the onChange event in the select box. This way, you can send the selected value to the server and have it stored in the session.

Answer №5

One possible approach is to utilize JavaScript in order to send arguments to a servlet class, and then establish a session within this servlet class.

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

Issue with Tanstack React Query failing to import

Attempting to integrate tanstack react query into my current project to handle state management has proven challenging. Following a tutorial on using react query with nextjs 13, I thought I was following it correctly. However, I encountered various import ...

struggling to modify hooks variable while fetching multiple URLs in React

I'm currently working on storing data from the TMDB movie API using a custom React hook. useFetch.js import {React, useState, useEffect} from 'react'; export default function useFetch() { const key = process.env.REACT_APP_API_KEY; ...

Transmitting flawless data to the Angular controller

In my Angular application, I have some checkboxes that are pre-checked and in the ng-pristine state. How can I receive these inputs in my controller without marking them as dirty when the form is submitted? <input type="checkbox" name="c1" name="favor ...

Is there a way to void a delayed input event?

After reading this How to delay the .keyup() handler until the user stops typing? post, we have grasped how to implement delays. However, is there any suggestion on how to cancel a delayed event? Take a look at this In the scenario given, I want nothing t ...

Extracting information from a JSON file using React.js

I have a JSON file named data.json in my React.js project: [{"id": 1,"title": "Child Bride"}, {"id": 2, "title": "Last Time I Committed Suicide, The"}, {"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, {"id": 4, ...

Error message: "Sonar detects a need for serialization or making transient"

Having this serializable class implemented as follows: public class Test implements Serializable{ private String id; private Map<String,Object> otherProperties; } Encountering issues with serialization due to the https://i.sstatic.net/6ap67.png ...

Is it possible to manipulate div elements with JavaScript while utilizing node.js?

It seems like I'm missing something obvious here, as I'm working with node.js and I have correctly linked a javascript file (alert("hello"); works). However, I can't seem to make any changes to the DOM. Here's a simple example: jade: ...

Multiple instances of Ajax requests being submitted

I am currently working on updating the validation for my forms. The validation itself is functioning properly, but I have encountered an issue where if no validation errors occur, the form submits multiple times based on the number of submission attempts b ...

Tips for successfully handling errors by passing variables

Hello there, Below is a function that I have: async function fnIsOnScreenOnce(img, desc,iCounter,client,repeatDelay=0) { await timeout(repeatDelay); let screenshot= await client.screenshot() let buf = new Buffer(screenshot.value, 'base64&apos ...

A problem arises when making an ajax call

I'm struggling with an Ajax call made using the jQuery .blur() method. Every time I try to execute it, an error message pops up. Any idea why this is happening? Here's my jQuery/Ajax Code: <script> $("#given_name").blur(function(){ va ...

Utilizing Vue.js watcher to replicate input fields causing a null pointer error

I'm currently facing an issue in Vue.js while trying to set up a watcher for duplicating an input based on certain conditions. I keep encountering null references when using the value property, and I would appreciate it if someone could explain why th ...

Struggling with extracting HTML page source with Java

My goal is to extract the HTML page source of a website in order to retrieve an email address. However, when I use a ripper or dumper tool, it only captures up to line 160 of the source code. I can manually access the webpage, right-click, and view the pag ...

Android 12 devices experiencing issues with Dialog cropping in Android applications

Our team has been encountering an issue with dialog clipping on certain devices, such as the Samsung TAB S7. Despite numerous attempts to resolve this problem consistently across all devices, we have not found a solution that works effectively. We have cre ...

Having trouble retrieving data from the React form

import React from 'react' import ThankYouModal from '../components/modals/ThankYouModal'; export default class ContactForm extends React.Component { constructor(props){ super(props); //inputs this.showOrgan ...

Create interactive charts with Highcharts by incorporating AJAX requests

Below is the code snippet for an AJAX request to retrieve data and then call a function to pass the data to a graph. function getGraphs(){ $.ajax({ type : "POST", async: true, url : "<?php echo base_url(); ?>" + "Graphs/get_graphs", ...

Saving data in local storage using an array

On my quiz page, I display one question at a time with the answers in buttons. When a button is clicked, the next question is loaded from the database. However, I faced an issue where the array containing the selected answers is emptied upon page reload. I ...

How can I sort through a complicated array in react native?

I am working with an array containing user data and their respective games. const arr = [{ "status": "success", "data": [{ "name": "user1", "games": [{ ...

Determine if the input is contained within an array using JavaScript

I'm new to JavaScript and need some help with arrays. My goal is to verify if the user's input value exists in an array named "fruits" that I have declared. If it does, I want to run a specific piece of code. However, if it doesn't exist in ...

Leveraging the power of CreateJS in partnership with Chart.js

Can anyone provide guidance on how to integrate a chartjs radar chart into a createjs canvas stage? I am attempting to use chartjs to generate the chart and then position it within the createjs stage. Any suggestions or advice would be greatly appreciate ...

Changing an ajax call to an AngularJS HTTP POST conversion

Recently, I've been encountering some issues with calling an existing WCF (non-RESTful) service using $.ajax and the $http service. No matter what I try, I can't seem to get it working properly. The snippet below shows that the service is returni ...