Nicolas Buster
Nicolas Buster

Reputation: 21

Get Spring @RequestParam in ajax request

I'm trying to get a Java object in my javascript. I'm using a ajax request to get this object. Here is my code :

@RequestMapping(path = "/sendSMS", method = RequestMethod.POST)
public void sendSMS(HttpServletRequest request, 
                    HttpServletResponse response, 
                    final ModelMap contactModel,
                    @RequestParam(value = "id") final String contactId) { ... }

and my ajax request :

var $this = $(this);
$.ajax({
    type : 'POST',
    url : '/contacts/sendSMS?id=${param.id}',
    data : $this.serialize(),
    dataType : 'json',
    success : function(json) {
        alert("success");
        $.each(json,function(index,element) {
            if (index == "message") {
                message = element;
                alert(message);
            }
        }
    }
})

The error I got in Eclipse is:

java.lang.NumberFormatException: For input string: "${param.id}"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at com.controller.contact.ContactController.sendSMS(ContactController.java:259)

This line is :

Integer id = Integer.parseInt(contactId);

EDIT : It works when I hard code the id. I just modify url like this :

var smsUrl = '/contacts/sendSMS?id=113';
url : smsUrl,

Now my problem is that I don't know how to get the id value dynamically.

Upvotes: 0

Views: 3857

Answers (4)

jjack
jjack

Reputation: 136

${param.id}

This value comes from Spring. JavaScript files should be seperated from JSP files. You can for example connect Spring variable to HTML tag in your JSP file like <form>:

<form myattribute="${param.id}">
... 
</form>

and now you can fetch this value in your JavaScript file with jQuery like this:

var myId = $('form').attr('myattribute');

$.ajax({ 
    type : 'POST',
    url : '/contacts/sendSMS?id=' + myId 
    ...
});

You can also use the data-* attribute to embed custom data in your HTML tags like:

 <form data-myvariable="${param.id}">
 ... 
 </form>

and then in JS file:

var myId = $('form').data("myvariable");

$.ajax({ 
    type : 'POST',
    url : '/contacts/sendSMS?id=' + myId 
    ...
});

Upvotes: 1

lradacher
lradacher

Reputation: 490

url : '/contacts/sendSMS?id='+${param.id}

should to the magic, but as you mentioned in earlier answers to you maybe mix JavaScript and JSPs ?

You might want also to take a look at: Reading a JSP variable from JavaScript

Upvotes: 0

Bhushan Bhangale
Bhushan Bhangale

Reputation: 10987

Change url : '/contacts/sendSMS?id=${param.id}' to url : '/contacts/sendSMS?id=' + ${param.id}

Upvotes: 1

hotzst
hotzst

Reputation: 7506

In your AJAX call you are defining the url as a static value, while the id should be dynamic. Change it to:

 url : '/contacts/sendSMS?id='+${param.id},

Upvotes: 0

Related Questions