DAVIDBALAS1 DAVIDBALAS1 - 6 months ago 9
Java Question

Assigning javascript variable to java variable

I know I can't use

javascript
variable inside
java
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
srcc
variable as it's assigned in
javascript
, this function called when I press a button in
jquery
, 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>");
$lightbox.append($img).append($caption).append($btn);
$('body').append($lightbox);
$('.gallery li').click(function(e) {
e.preventDefault();
var src = $(this).children('img').attr("src");
var cap = $(this).children('img').attr("alt");
$btn.off('click').on('click', function(da) {
$(document).ready(function() {
init(src);
});
});
$img.attr('src', src);
$caption.text(cap);
$lightbox.fadeIn('fast');
$lightbox.click(function() {
$lightbox.fadeOut('fast');
});
});


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. (
srcc
equals what he added and
session.getAttribute("currentuser")
is whom added).
Thanks guys.

Answer

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
});
Comments