Francis Francis - 1 year ago 78
Ajax Question

Trying to post more than one variable via xmlhttprequest of ajax to the controller

In my java application. I am trying to post more two javascript variable to via a xmlhttp post request of ajax but it is returning error 400. Ordinarily, if I comment out one of the post variables, then it posts successfully but on adding it, throws error. This is my attempt:

function sendChat() {
var message = document.getElementById('new-input').value.trim();
var noteVal = "mp3",
xhr = new XMLHttpRequest();


xhr.send(encodeURI('message=' + message));
xhr.send(encodeURI('noteVal=' + noteVal)); //if I comment this out then everything is fine

this is the spring controller to receive the post arguments

@RequestMapping(value = "/post-data", method = RequestMethod.POST)
public ModelAndView postData(HttpServletRequest request,
HttpServletResponse response,
@RequestParam String message,
@RequestParam String noteVal,

Please how can I post more than one variables to the controller method via XMLHttpRequest

Answer Source

You can only send once, so you send both values

xhr.send('message=' + encodeURI(message) + '&noteVal=' + encodeURI(noteVal));

or sending formData

var data = new FormData();
data.append('message', message);
data.append('noteVal', noteVal);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download