Itsik Mauyhas
Itsik Mauyhas

Reputation: 3984

JSP send Java variables by ajax

I want to send JSP java variables that I had defined via ajax request, it it possible?

My JSP :

<%
    String fileName = (String)request.getAttribute(MatafConstants.PARAM_IMG_FILE_NAMES);
%>

And then I want to send this String:

    $.ajax({
                  url: "/some/urlServlet",
                  type: "get", //send it through get method
                  data: { 
                    "statusID": status, 
                    "test": '<%=fileName%>' //here is the param I send
                  },
                  success: function(response) {
                    //Do Something
                    console.log(response);
                  },
                  error: function(xhr) {
                    //Do Something to handle error
                  }
 });

How can I sent this param? Or the bigger question I can I use JSP java variable in JavaScript?

Upvotes: 0

Views: 3487

Answers (2)

D Sai Krishna
D Sai Krishna

Reputation: 21

Answer is YES. and your request looks correct. But make sure you add the AJAX call in the same page where that variable you are initiating.

<jsp:declaration>
    String name=null;
    String role=null;
    String company=null;
</jsp:declaration>
<jsp:scriptlet>
    if(request.getSession().getAttribute("username")==null){
        response.sendRedirect("../login.jsp");
    }
    else{
        name=(String)request.getSession().getAttribute("username");
        role= (String)request.getSession().getAttribute("role");
        company=(String)request.getSession().getAttribute("company");
    }
</jsp:scriptlet>

in javascript on the same page:

<script>
            var name="<jsp:expression>name</jsp:expression>";
            var company="<jsp:expression>company </jsp:expression>";
</script>

Upvotes: 0

Yaroslav Boichuk
Yaroslav Boichuk

Reputation: 1776

You can create hidden field with value from scriplet, and then use it's value in Java Script. Something like below:

JSP code

<input type="hidden" id="fileName" value="<%=(String)request.getAttribute(MatafConstants.PARAM_IMG_FILE_NAMES)%>">

Java script code

data: { 
    "statusID": status, 
    "test": document.getElementById("fileName").value;
},

Upvotes: 1

Related Questions