DAVIDBALAS1 DAVIDBALAS1 - 2 years ago 78
Java Question

Assigning javascript variable to java variable

I know I can't use

variable inside
code so can anyone explain me what I can do instead?

function init(srcc) {
<%if (session.getAttribute("status") != null && session.getAttribute("status").equals("member")) {%>
alert(srcc + " ");
<%application.setAttribute(session.getAttribute("currentuser"), srcc);%>

in this line:

<%application.setAttribute(session.getAttribute("currentuser"), srcc);%>

I can't read the
variable as it's assigned in
, this function called when I press a button in
, code:

var $lightbox = $("<div class='lightbox'></div>");
var $img = $("<img>");
var $caption = $("<p class='caption'></p>");
var $btn = $("<div align='center'> <INPUT TYPE='BUTTON' VALUE='Add to cart'></div>");
$('.gallery li').click(function(e) {
var src = $(this).children('img').attr("src");
var cap = $(this).children('img').attr("alt");
$btn.off('click').on('click', function(da) {
$(document).ready(function() {
$img.attr('src', src);
$lightbox.click(function() {

I use it in an "add to cart" button, I want the server to keep data of whom added it to the cart and what he added. (
equals what he added and
is whom added).
Thanks guys.

Answer Source

You can send that JavaScript variable to Java using an AJAX request

You would have to have a serverside route set up to handle this request coming in and process the sent data.

Since I already see jQuery being used in your code, I'll use this AJAX function in my example code. You can send an HTTP request without your browser reloading the page in this way:

$.get("/urlOfCartHandler/?parameterName=" + javaScriptVariableContainingDataYouWantToSend, function(data) {
    //Request was a success
}).fail(function() {
    //Request failed
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download