user3469203
user3469203

Reputation: 547

Access JSTL variable define in a jsp inside AJAX call

I got a JSP file where I define JSTL variable like this (form value) :

<c:set var="idEtape" value="${etapeForm.etape.idEtape}" scope="page"/>
<c:set var="idContact" value="${etapeForm.etape.idContact}" scope="page"/>
<c:set var="numeroDossierFoa" value="${etapeForm.dossier.numeroDossier}" scope="page"/>
<script type="text/javascript" src=myfile.js"/>"></script>

In my myfile.js file, I need to use these variable but I got an error who tell me that they are undefined.

I use these variables in an ajax call like this :

var request = $.ajax({
            type: "POST",
            url: "/myUrl/" + numeroDossier + "/" + idContact + "/" + idEtape,
            cache: false
});

Where am I wrong ?

Upvotes: 1

Views: 7763

Answers (3)

user2575725
user2575725

Reputation:

You may try using ${} to access jstl variables. In your jsp create js variables before the file import:

jsp

<script type="text/javascript">
    var numeroDossier = '${etapeForm.dossier.numeroDossier}';
    var idEtape = '${etapeForm.etape.idEtape}';
    var idContact = '${etapeForm.etape.idContact}';
</script>
<script type="text/javascript" src=myfile.js"/>"></script>

js

var request = $.ajax(
{
    type: "POST",
    url: "/myUrl/" + numeroDossier + "/" + idContact + "/" +idEtape,
    cache: false
});

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You have to use EL expression to access this variable like below, provided that variable scope should be session :

<c:set var="idEtape" value="${etapeForm.etape.idEtape}" scope="session"/>
<c:set var="idContact" value="${etapeForm.etape.idContact}" scope="session"/>
<c:set var="numeroDossierFoa" value="${etapeForm.dossier.numeroDossier}" scope="session"/>

var request = $.ajax({type: "POST",
    url: "/myUrl/" + '${numeroDossier}' + "/" + '${idContact}' + "/" + '${idEtape}',
    cache: false
    });

Upvotes: 0

Nikhil Talreja
Nikhil Talreja

Reputation: 2774

JSP variables cannot be used inside javascript file since JSP is server side and JS is client side

Try this:

<input id="idEtape" value="${etapeForm.etape.idEtape}" type="hidden"/>

In JS:

$("#idEtape").val();

Upvotes: 5

Related Questions