NewUser
NewUser

Reputation: 3819

How to add JSP variable in jQuery?

I am getting some JSON data from a file db.jsp. The jsp file gets user details from my database and prints as a JSON format I am using get method to achieve this.

My url should be like : db.jsp?userid=DIBYA the value 'DIBYA' here is input form the user. I am trying to concatenate as:

function submit() {
    $.getJSON('db.jsp?userid='+<%String userName = request.getParameter("userid"); out.print(userName);%>, function(data) {

But, my console shows an error message as ReferenceError: DIBYA is not defined. Please tell me what changes do I need in my code?

Thanks

Dibya

Upvotes: 1

Views: 1379

Answers (2)

&#201;tienne Miret
&#201;tienne Miret

Reputation: 6660

You forgot to put quotes around “DIBYA”. Your code expands to:

function submit() {
    $.getJSON('db.jsp?userid='+DIBYA, function(data) {

but you want:

function submit() {
    $.getJSON('db.jsp?userid='+'DIBYA', function(data) {

or better:

function submit() {
    $.getJSON('db.jsp?userid=DIBYA', function(data) {

So you need to write like that:

function submit() {
    $.getJSON('db.jsp?userid=<% out.print(userName);%>', function(data) {

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691973

The following line

$.getJSON('db.jsp?userid='+<%String userName = "DIBYA"; out.print(userName);%>, function(data) {

will be translated by the JSP container to the following JavaScript code:

$.getJSON('db.jsp?userid='+DIBYA, function(data) {

So the JavaScript engine in the browser will look for a JavaScript variable named DIBYA.

If you just want the value to be the string DIBYA, I don't even understand why you use a scriptlet. Just use

$.getJSON('db.jsp?userid=DIBYA', function(data) {

Upvotes: 0

Related Questions